Windows: Correct alloc size SetFileExtents result
[openafs.git] / src / WINNT / afsrdr / user / RDRFunction.c
1 /*
2  * Copyright (c) 2008 Secure Endpoints, Inc.
3  * Copyright (c) 2009-2011 Your File System, Inc.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * - Redistributions of source code must retain the above copyright notice,
10  *   this list of conditions and the following disclaimer.
11  * - Redistributions in binary form must reproduce the above copyright notice,
12  *   this list of conditions and the following disclaimer in the documentation
13  *   and/or other materials provided with the distribution.
14  * - Neither the name of Secure Endpoints Inc. nor the names of its contributors
15  *   may be used to endorse or promote products derived from this software without
16  *   specific prior written permission from Secure Endpoints, Inc. and
17  *   Your File System, Inc.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
22  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
23  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include <afsconfig.h>
33 #include <afs/param.h>
34
35 #ifndef _WIN32_WINNT
36 #define _WIN32_WINNT 0x0500
37 #endif
38 #define _CRT_SECURE_NO_DEPRECATE
39 #define _CRT_NON_CONFORMING_SWPRINTFS
40 #define INITGUID        /* define AFS_AUTH_GUID_NO_PAG */
41
42 #include <ntstatus.h>
43 #define WIN32_NO_STATUS
44 #include <windows.h>
45
46 #include <roken.h>
47
48 #include <afs/stds.h>
49
50 #include <ntsecapi.h>
51 #include <sddl.h>
52 #pragma warning(push)
53 #pragma warning(disable: 4005)
54
55 #include <devioctl.h>
56
57 #include "..\\Common\\AFSUserDefines.h"
58 #include "..\\Common\\AFSUserStructs.h"
59
60 #pragma warning(pop)
61
62 #include <tchar.h>
63 #include <wchar.h>
64 #include <winbase.h>
65 #include <winreg.h>
66
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <stdarg.h>
70 #include <strsafe.h>
71
72 #include "afsd.h"
73 #include "smb.h"
74 #include "cm_btree.h"
75 #include "msrpc.h"
76 #include <RDRPrototypes.h>
77 #include <RDRIoctl.h>
78 #include <RDRPipe.h>
79
80 static CHAR * RDR_extentBaseAddress = NULL;
81
82 void
83 RDR_InitReq(cm_req_t *reqp, BOOL bWow64)
84 {
85     cm_InitReq(reqp);
86     reqp->flags |= CM_REQ_SOURCE_REDIR;
87     if (bWow64)
88         reqp->flags |= CM_REQ_WOW64;
89 }
90
91 void
92 RDR_fid2FID( cm_fid_t *fid, AFSFileID *FileId)
93 {
94     FileId->Cell = fid->cell;
95     FileId->Volume = fid->volume;
96     FileId->Vnode = fid->vnode;
97     FileId->Unique = fid->unique;
98     FileId->Hash = fid->hash;
99 }
100
101 void
102 RDR_FID2fid( AFSFileID *FileId, cm_fid_t *fid)
103 {
104     fid->cell = FileId->Cell;
105     fid->volume = FileId->Volume;
106     fid->vnode = FileId->Vnode;
107     fid->unique = FileId->Unique;
108     fid->hash = FileId->Hash;
109 }
110
111 DWORD
112 RDR_SetInitParams( OUT AFSRedirectorInitInfo **ppRedirInitInfo, OUT DWORD * pRedirInitInfoLen )
113 {
114     extern char cm_CachePath[];
115     extern cm_config_data_t cm_data;
116     extern int smb_hideDotFiles;
117     size_t cm_CachePathLen = strlen(cm_CachePath);
118     size_t err;
119     DWORD TempPathLen = ExpandEnvironmentStringsW(L"%TEMP%", NULL, 0);
120     MEMORYSTATUSEX memStatus;
121     DWORD maxMemoryCacheSize;
122
123     memStatus.dwLength = sizeof(memStatus);
124     if (GlobalMemoryStatusEx(&memStatus)) {
125         /*
126          * Use the memory extent interface in the afs redirector
127          * whenever the cache size is less than equal to 10% of
128          * physical memory.  Do not use too much because this memory
129          * will be locked by the redirector so it can't be swapped
130          * out.
131          */
132         maxMemoryCacheSize = (DWORD)(memStatus.ullTotalPhys / 1024 / 10);
133     } else {
134         /*
135          * If we can't determine the amount of physical memory
136          * in the system, be conservative and limit the use of
137          * memory extent interface to 64MB data caches.
138          */
139         maxMemoryCacheSize = 65536;
140     }
141
142     *pRedirInitInfoLen = (DWORD) (sizeof(AFSRedirectorInitInfo) + (cm_CachePathLen + TempPathLen) * sizeof(WCHAR));
143     *ppRedirInitInfo = (AFSRedirectorInitInfo *)malloc(*pRedirInitInfoLen);
144     (*ppRedirInitInfo)->Flags = smb_hideDotFiles ? AFS_REDIR_INIT_FLAG_HIDE_DOT_FILES : 0;
145     (*ppRedirInitInfo)->Flags |= cm_shortNames ? 0 : AFS_REDIR_INIT_FLAG_DISABLE_SHORTNAMES;
146     (*ppRedirInitInfo)->MaximumChunkLength = cm_data.chunkSize;
147     (*ppRedirInitInfo)->GlobalFileId.Cell   = cm_data.rootFid.cell;
148     (*ppRedirInitInfo)->GlobalFileId.Volume = cm_data.rootFid.volume;
149     (*ppRedirInitInfo)->GlobalFileId.Vnode  = cm_data.rootFid.vnode;
150     (*ppRedirInitInfo)->GlobalFileId.Unique = cm_data.rootFid.unique;
151     (*ppRedirInitInfo)->GlobalFileId.Hash   = cm_data.rootFid.hash;
152     (*ppRedirInitInfo)->ExtentCount.QuadPart = cm_data.buf_nbuffers;
153     (*ppRedirInitInfo)->CacheBlockSize = cm_data.blockSize;
154     (*ppRedirInitInfo)->MaxPathLinkCount = MAX_FID_COUNT;
155     (*ppRedirInitInfo)->NameArrayLength = MAX_FID_COUNT;
156     if (cm_virtualCache || cm_data.bufferSize <= maxMemoryCacheSize) {
157         osi_Log0(afsd_logp, "RDR_SetInitParams Initializing Memory Extent Interface");
158         (*ppRedirInitInfo)->MemoryCacheOffset.QuadPart = (LONGLONG)cm_data.bufDataBaseAddress;
159         (*ppRedirInitInfo)->MemoryCacheLength.QuadPart = cm_data.bufEndOfData - cm_data.bufDataBaseAddress;
160         (*ppRedirInitInfo)->CacheFileNameLength = 0;
161         RDR_extentBaseAddress = cm_data.bufDataBaseAddress;
162     } else {
163         (*ppRedirInitInfo)->MemoryCacheOffset.QuadPart = 0;
164         (*ppRedirInitInfo)->MemoryCacheLength.QuadPart = 0;
165         (*ppRedirInitInfo)->CacheFileNameLength = (ULONG) (cm_CachePathLen * sizeof(WCHAR));
166         err = mbstowcs((*ppRedirInitInfo)->CacheFileName, cm_CachePath, (cm_CachePathLen + 1) *sizeof(WCHAR));
167         if (err == -1) {
168             free(*ppRedirInitInfo);
169             osi_Log0(afsd_logp, "RDR_SetInitParams Invalid Object Name");
170             return STATUS_OBJECT_NAME_INVALID;
171         }
172         RDR_extentBaseAddress = cm_data.baseAddress;
173     }
174     (*ppRedirInitInfo)->DumpFileLocationOffset = FIELD_OFFSET(AFSRedirectorInitInfo, CacheFileName) + (*ppRedirInitInfo)->CacheFileNameLength;
175     (*ppRedirInitInfo)->DumpFileLocationLength = (TempPathLen - 1) * sizeof(WCHAR);
176     ExpandEnvironmentStringsW(L"%TEMP%",
177                               (LPWSTR)(((PBYTE)(*ppRedirInitInfo)) + (*ppRedirInitInfo)->DumpFileLocationOffset),
178                               TempPathLen);
179
180     osi_Log0(afsd_logp,"RDR_SetInitParams Success");
181     return 0;
182 }
183
184 static wchar_t cname[MAX_COMPUTERNAME_LENGTH+1] = L"";
185
186 cm_user_t *
187 RDR_GetLocalSystemUser( void)
188 {
189     smb_username_t *unp;
190     cm_user_t *userp = NULL;
191
192     if ( cname[0] == '\0') {
193         int len = MAX_COMPUTERNAME_LENGTH+1;
194         GetComputerNameW(cname, &len);
195         _wcsupr(cname);
196     }
197     unp = smb_FindUserByName(NTSID_LOCAL_SYSTEM, cname, SMB_FLAG_CREATE);
198     lock_ObtainMutex(&unp->mx);
199     if (!unp->userp)
200         unp->userp = cm_NewUser();
201     unp->flags |= SMB_USERNAMEFLAG_SID;
202     lock_ReleaseMutex(&unp->mx);
203     userp = unp->userp;
204     cm_HoldUser(userp);
205     smb_ReleaseUsername(unp);
206
207     if (!userp) {
208         userp = cm_rootUserp;
209         cm_HoldUser(userp);
210     }
211
212     return userp;
213 }
214
215 cm_user_t *
216 RDR_UserFromCommRequest( IN AFSCommRequest *RequestBuffer)
217 {
218
219     return RDR_UserFromAuthGroup( &RequestBuffer->AuthGroup);
220 }
221
222 cm_user_t *
223 RDR_UserFromAuthGroup( IN GUID *pGuid)
224 {
225     smb_username_t *unp;
226     cm_user_t * userp = NULL;
227     RPC_WSTR UuidString = NULL;
228
229     if (UuidToStringW((UUID *)pGuid, &UuidString) != RPC_S_OK)
230         goto done;
231
232     if ( cname[0] == '\0') {
233         int len = MAX_COMPUTERNAME_LENGTH+1;
234         GetComputerNameW(cname, &len);
235         _wcsupr(cname);
236     }
237
238     unp = smb_FindUserByName(UuidString, cname, SMB_FLAG_CREATE);
239     lock_ObtainMutex(&unp->mx);
240     if (!unp->userp) {
241         unp->userp = cm_NewUser();
242         memcpy(&unp->userp->authgroup, pGuid, sizeof(GUID));
243     }
244     unp->flags |= SMB_USERNAMEFLAG_SID;
245     lock_ReleaseMutex(&unp->mx);
246     userp = unp->userp;
247     cm_HoldUser(userp);
248     smb_ReleaseUsername(unp);
249
250   done:
251     if (!userp) {
252         userp = cm_rootUserp;
253         cm_HoldUser(userp);
254     }
255
256     osi_Log2(afsd_logp, "RDR_UserFromCommRequest Guid %S userp = 0x%p",
257              osi_LogSaveStringW(afsd_logp, UuidString),
258              userp);
259
260     if (UuidString)
261         RpcStringFreeW(&UuidString);
262
263     return userp;
264 }
265
266 void
267 RDR_ReleaseUser( IN cm_user_t *userp )
268 {
269     osi_Log1(afsd_logp, "RDR_ReleaseUser userp = 0x%p", userp);
270     cm_ReleaseUser(userp);
271 }
272
273
274 /*
275  * RDR_FlagScpInUse flags the scp with CM_SCACHEFLAG_RDR_IN_USE
276  */
277 static void
278 RDR_FlagScpInUse( IN cm_scache_t *scp, IN BOOL bLocked )
279 {
280     if (!bLocked)
281         lock_ObtainWrite(&scp->rw);
282
283     lock_AssertWrite(&scp->rw);
284     scp->flags |= CM_SCACHEFLAG_RDR_IN_USE;
285
286     if (!bLocked)
287         lock_ReleaseWrite(&scp->rw);
288 }
289
290 /*
291  * Obtain the status information for the specified object using
292  * an inline bulk status rpc.  cm_BPlusDirEnumBulkStatOne() will
293  * obtain current status for the directory object, the object
294  * which is the focus of the inquiry and as many other objects
295  * in the directory for which there are not callbacks registered
296  * since we are likely to be asked for other objects in the directory.
297  */
298 static afs_uint32
299 RDR_BulkStatLookup( cm_scache_t *dscp,
300                     cm_scache_t *scp,
301                     cm_user_t   *userp,
302                     cm_req_t    *reqp)
303 {
304     cm_direnum_t *      enump = NULL;
305     afs_uint32  code = 0;
306     cm_dirOp_t    dirop;
307
308     code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
309     if (code == 0) {
310         code = cm_BPlusDirEnumerate(dscp, userp, reqp, TRUE, NULL, TRUE, &enump);
311         if (code) {
312             osi_Log1(afsd_logp, "RDR_BulkStatLookup cm_BPlusDirEnumerate failure code=0x%x",
313                       code);
314         }
315         cm_EndDirOp(&dirop);
316     } else {
317         osi_Log1(afsd_logp, "RDR_BulkStatLookup cm_BeginDirOp failure code=0x%x",
318                   code);
319     }
320
321     if (enump)
322     {
323         code = cm_BPlusDirEnumBulkStatOne(enump, scp);
324         if (code) {
325             osi_Log1(afsd_logp, "RDR_BulkStatLookup cm_BPlusDirEnumBulkStatOne failure code=0x%x",
326                       code);
327         }
328         cm_BPlusDirFreeEnumeration(enump);
329     }
330
331     return code;
332 }
333
334
335 #define RDR_POP_FOLLOW_MOUNTPOINTS 0x01
336 #define RDR_POP_EVALUATE_SYMLINKS  0x02
337 #define RDR_POP_WOW64              0x04
338 #define RDR_POP_NO_GETSTATUS       0x08
339
340 static afs_uint32
341 RDR_PopulateCurrentEntry( IN  AFSDirEnumEntry * pCurrentEntry,
342                           IN  DWORD             dwMaxEntryLength,
343                           IN  cm_scache_t     * dscp,
344                           IN  cm_scache_t     * scp,
345                           IN  cm_user_t       * userp,
346                           IN  cm_req_t        * reqp,
347                           IN  wchar_t         * name,
348                           IN  wchar_t         * shortName,
349                           IN  DWORD             dwFlags,
350                           IN  afs_uint32        cmError,
351                           OUT AFSDirEnumEntry **ppNextEntry,
352                           OUT DWORD           * pdwRemainingLength)
353 {
354     FILETIME ft;
355     WCHAR *  wname, *wtarget;
356     size_t   len;
357     DWORD      dwEntryLength;
358     afs_uint32 code = 0, code2 = 0;
359     BOOL          bMustFake = FALSE;
360
361     osi_Log5(afsd_logp, "RDR_PopulateCurrentEntry dscp=0x%p scp=0x%p name=%S short=%S flags=0x%x",
362              dscp, scp, osi_LogSaveStringW(afsd_logp, name),
363              osi_LogSaveStringW(afsd_logp, shortName), dwFlags);
364     osi_Log1(afsd_logp, "... maxLength=%d", dwMaxEntryLength);
365
366     if (dwMaxEntryLength < sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t)) {
367         if (ppNextEntry)
368             *ppNextEntry = pCurrentEntry;
369         if (pdwRemainingLength)
370             *pdwRemainingLength = dwMaxEntryLength;
371         osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry Not Enough Room for Entry %d < %d",
372                  dwMaxEntryLength, sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t));
373         return CM_ERROR_TOOBIG;
374     }
375
376     if (!name)
377         name = L"";
378     if (!shortName)
379         shortName = L"";
380
381     dwEntryLength = sizeof(AFSDirEnumEntry);
382
383     lock_ObtainWrite(&scp->rw);
384     if (dwFlags & RDR_POP_NO_GETSTATUS) {
385         if (!cm_HaveCallback(scp))
386             bMustFake = TRUE;
387     } else {
388 #ifdef AFS_FREELANCE_CLIENT
389         if (scp->fid.cell == AFS_FAKE_ROOT_CELL_ID && scp->fid.volume == AFS_FAKE_ROOT_VOL_ID) {
390             /*
391              * If the FID is from the Freelance Local Root always perform
392              * a single item status check.
393              */
394             code = cm_SyncOp( scp, NULL, userp, reqp, 0,
395                               CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
396             if (code) {
397                 lock_ReleaseWrite(&scp->rw);
398                 osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_SyncOp failed for scp=0x%p code=0x%x",
399                          scp, code);
400                 return code;
401             }
402         } else
403 #endif
404         {
405             /*
406              * For non-Freelance objects, check to see if we have current
407              * status information.  If not, perform a bulk status lookup of multiple
408              * entries in order to reduce the number of RPCs issued to the file server.
409              */
410             if (cm_EAccesFindEntry(userp, &scp->fid))
411                 bMustFake = TRUE;
412             else if (!cm_HaveCallback(scp)) {
413                 lock_ReleaseWrite(&scp->rw);
414                 code = RDR_BulkStatLookup(dscp, scp, userp, reqp);
415                 if (code) {
416                     osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry RDR_BulkStatLookup failed for scp=0x%p code=0x%x",
417                              scp, code);
418                     return code;
419                 }
420                 lock_ObtainWrite(&scp->rw);
421                 /*
422                  * RDR_BulkStatLookup can succeed but it may be the case that there
423                  * still is not valid status info.  If we get this far, generate fake
424                  * status info.
425                  */
426                 if (!cm_HaveCallback(scp))
427                     bMustFake = TRUE;
428             }
429         }
430     }
431
432     /* Populate the error code */
433     smb_MapNTError(cmError, &pCurrentEntry->NTStatus, TRUE);
434
435     /* Populate the real or fake data */
436     pCurrentEntry->FileId.Cell = scp->fid.cell;
437     pCurrentEntry->FileId.Volume = scp->fid.volume;
438     pCurrentEntry->FileId.Vnode = scp->fid.vnode;
439     pCurrentEntry->FileId.Unique = scp->fid.unique;
440     pCurrentEntry->FileId.Hash = scp->fid.hash;
441
442     pCurrentEntry->FileType = scp->fileType;
443
444     pCurrentEntry->DataVersion.QuadPart = scp->dataVersion;
445
446     if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
447         scp->fid.volume==AFS_FAKE_ROOT_VOL_ID) {
448         cm_LargeSearchTimeFromUnixTime(&ft, MAX_AFS_UINT32);
449     } else {
450         cm_LargeSearchTimeFromUnixTime(&ft, scp->cbExpires);
451     }
452     pCurrentEntry->Expiration.LowPart = ft.dwLowDateTime;
453     pCurrentEntry->Expiration.HighPart = ft.dwHighDateTime;
454
455     if (bMustFake) {
456         /* 1969-12-31 23:59:59 +00 */
457         ft.dwHighDateTime = 0x19DB200;
458         ft.dwLowDateTime = 0x5BB78980;
459     } else
460         cm_LargeSearchTimeFromUnixTime(&ft, scp->clientModTime);
461     pCurrentEntry->CreationTime.LowPart = ft.dwLowDateTime;
462     pCurrentEntry->CreationTime.HighPart = ft.dwHighDateTime;
463     pCurrentEntry->LastAccessTime = pCurrentEntry->CreationTime;
464     pCurrentEntry->LastWriteTime = pCurrentEntry->CreationTime;
465     pCurrentEntry->ChangeTime = pCurrentEntry->CreationTime;
466
467     pCurrentEntry->EndOfFile = scp->length;
468     pCurrentEntry->AllocationSize = scp->length;
469
470     if (bMustFake) {
471         switch (scp->fileType) {
472         case CM_SCACHETYPE_DIRECTORY:
473             pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY;
474             break;
475         case CM_SCACHETYPE_MOUNTPOINT:
476         case CM_SCACHETYPE_INVALID:
477             pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY | SMB_ATTR_REPARSE_POINT;
478             break;
479         case CM_SCACHETYPE_SYMLINK:
480             if (cm_TargetPerceivedAsDirectory(scp->mountPointStringp))
481                 pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY | SMB_ATTR_REPARSE_POINT;
482             else
483                 pCurrentEntry->FileAttributes = SMB_ATTR_REPARSE_POINT;
484             break;
485         default:
486             /* if we get here we either have a normal file
487             * or we have a file for which we have never
488             * received status info.  In this case, we can
489             * check the even/odd value of the entry's vnode.
490             * odd means it is to be treated as a directory
491             * and even means it is to be treated as a file.
492             */
493             if (scp->fid.vnode & 0x1)
494                 pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY;
495             else
496                 pCurrentEntry->FileAttributes = SMB_ATTR_NORMAL;
497         }
498     } else
499         pCurrentEntry->FileAttributes = smb_ExtAttributes(scp);
500     pCurrentEntry->EaSize = 0;
501     pCurrentEntry->Links = scp->linkCount;
502
503     len = wcslen(shortName);
504     wcsncpy(pCurrentEntry->ShortName, shortName, len);
505     pCurrentEntry->ShortNameLength = (CCHAR)(len * sizeof(WCHAR));
506
507     pCurrentEntry->FileNameOffset = sizeof(AFSDirEnumEntry);
508     len = wcslen(name);
509     wname = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->FileNameOffset);
510     wcsncpy(wname, name, len);
511     pCurrentEntry->FileNameLength = (ULONG)(sizeof(WCHAR) * len);
512
513     osi_Log3(afsd_logp, "RDR_PopulateCurrentEntry scp=0x%p fileType=%d dv=%u",
514               scp, scp->fileType, (afs_uint32)scp->dataVersion);
515
516     if (!(dwFlags & RDR_POP_NO_GETSTATUS))
517         cm_SyncOpDone( scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
518
519     if ((dwFlags & RDR_POP_NO_GETSTATUS) || !cm_HaveCallback(scp)) {
520         pCurrentEntry->TargetNameOffset = 0;
521         pCurrentEntry->TargetNameLength = 0;
522     }
523     else
524     switch (scp->fileType) {
525     case CM_SCACHETYPE_MOUNTPOINT:
526         if (dwFlags & RDR_POP_FOLLOW_MOUNTPOINTS) {
527             if ((code2 = cm_ReadMountPoint(scp, userp, reqp)) == 0) {
528                 cm_scache_t *targetScp = NULL;
529
530                 pCurrentEntry->TargetNameOffset = pCurrentEntry->FileNameOffset + pCurrentEntry->FileNameLength;
531                 len = strlen(scp->mountPointStringp);
532                 wtarget = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->TargetNameOffset);
533
534 #ifdef UNICODE
535                 cch = MultiByteToWideChar( CP_UTF8, 0, scp->mountPointStringp,
536                                            len * sizeof(char),
537                                            wtarget,
538                                            len * sizeof(WCHAR));
539 #else
540                 mbstowcs(wtarget, scp->mountPointStringp, len);
541 #endif
542                 pCurrentEntry->TargetNameLength = (ULONG)(sizeof(WCHAR) * len);
543
544                 code2 = cm_FollowMountPoint(scp, dscp, userp, reqp, &targetScp);
545
546                 if (code2 == 0) {
547                     pCurrentEntry->TargetFileId.Cell = targetScp->fid.cell;
548                     pCurrentEntry->TargetFileId.Volume = targetScp->fid.volume;
549                     pCurrentEntry->TargetFileId.Vnode = targetScp->fid.vnode;
550                     pCurrentEntry->TargetFileId.Unique = targetScp->fid.unique;
551                     pCurrentEntry->TargetFileId.Hash = targetScp->fid.hash;
552
553                     osi_Log4(afsd_logp, "RDR_PopulateCurrentEntry target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
554                               pCurrentEntry->TargetFileId.Cell, pCurrentEntry->TargetFileId.Volume,
555                               pCurrentEntry->TargetFileId.Vnode, pCurrentEntry->TargetFileId.Unique);
556
557                     cm_ReleaseSCache(targetScp);
558                 } else {
559                     osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_FollowMountPoint failed scp=0x%p code=0x%x",
560                               scp, code2);
561                 }
562             } else {
563                 osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_ReadMountPoint failed scp=0x%p code=0x%x",
564                           scp, code2);
565             }
566         }
567         break;
568     case CM_SCACHETYPE_SYMLINK:
569     case CM_SCACHETYPE_DFSLINK:
570         {
571             pCurrentEntry->TargetNameOffset = pCurrentEntry->FileNameOffset + pCurrentEntry->FileNameLength;
572             wtarget = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->TargetNameOffset);
573
574             if (dwFlags & RDR_POP_EVALUATE_SYMLINKS) {
575                 char * mp;
576
577                 code2 = cm_HandleLink(scp, userp, reqp);
578                 if (code2 == 0) {
579                     mp = scp->mountPointStringp;
580                     len = strlen(mp);
581                     if ( len != 0 ) {
582                         /* Strip off the msdfs: prefix from the target name for the file system */
583                         if (scp->fileType == CM_SCACHETYPE_DFSLINK) {
584                             osi_Log0(afsd_logp, "RDR_PopulateCurrentEntry DFSLink Detected");
585                             pCurrentEntry->FileType = scp->fileType;
586
587                             if (!strncmp("msdfs:", mp, 6)) {
588                                 mp += 6;
589                                 len -= 6;
590                             }
591                         }
592                         /* only send one slash to the redirector */
593                         if (mp[0] == '\\' && mp[1] == '\\') {
594                             mp++;
595                             len--;
596                         }
597 #ifdef UNICODE
598                         cch = MultiByteToWideChar( CP_UTF8, 0, mp,
599                                                    len * sizeof(char),
600                                                    wtarget,
601                                                    len * sizeof(WCHAR));
602 #else
603                         mbstowcs(wtarget, mp, len);
604 #endif
605                     }
606                     pCurrentEntry->TargetNameLength = (ULONG)(sizeof(WCHAR) * len);
607                 } else {
608                     osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_HandleLink failed scp=0x%p code=0x%x",
609                              scp, code2);
610                 }
611             }
612
613         }
614         break;
615
616     default:
617         pCurrentEntry->TargetNameOffset = 0;
618         pCurrentEntry->TargetNameLength = 0;
619     }
620     lock_ReleaseWrite(&scp->rw);
621
622     dwEntryLength += pCurrentEntry->FileNameLength + pCurrentEntry->TargetNameLength;
623     dwEntryLength += (dwEntryLength % 8) ? 8 - (dwEntryLength % 8) : 0;   /* quad align */
624     if (ppNextEntry)
625         *ppNextEntry = (AFSDirEnumEntry *)((PBYTE)pCurrentEntry + dwEntryLength);
626     if (pdwRemainingLength)
627         *pdwRemainingLength = dwMaxEntryLength - dwEntryLength;
628
629     osi_Log3(afsd_logp, "RDR_PopulateCurrentEntry Success FileNameLength=%d TargetNameLength=%d RemainingLength=%d",
630               pCurrentEntry->FileNameLength, pCurrentEntry->TargetNameLength, *pdwRemainingLength);
631
632     return code;
633 }
634
635 static afs_uint32
636 RDR_PopulateCurrentEntryNoScp( IN  AFSDirEnumEntry * pCurrentEntry,
637                                IN  DWORD             dwMaxEntryLength,
638                                IN  cm_scache_t     * dscp,
639                                IN  cm_fid_t        * fidp,
640                                IN  cm_user_t       * userp,
641                                IN  cm_req_t        * reqp,
642                                IN  wchar_t         * name,
643                                IN  wchar_t         * shortName,
644                                IN  DWORD             dwFlags,
645                                IN  afs_uint32        cmError,
646                                OUT AFSDirEnumEntry **ppNextEntry,
647                                OUT DWORD           * pdwRemainingLength)
648 {
649     FILETIME ft;
650     WCHAR *  wname;
651     size_t   len;
652     DWORD      dwEntryLength;
653     afs_uint32 code = 0, code2 = 0;
654
655     osi_Log4(afsd_logp, "RDR_PopulateCurrentEntryNoEntry dscp=0x%p name=%S short=%S flags=0x%x",
656              dscp, osi_LogSaveStringW(afsd_logp, name),
657              osi_LogSaveStringW(afsd_logp, shortName), dwFlags);
658     osi_Log1(afsd_logp, "... maxLength=%d", dwMaxEntryLength);
659
660     if (dwMaxEntryLength < sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t)) {
661         if (ppNextEntry)
662             *ppNextEntry = pCurrentEntry;
663         if (pdwRemainingLength)
664             *pdwRemainingLength = dwMaxEntryLength;
665         osi_Log2(afsd_logp, "RDR_PopulateCurrentEntryNoEntry Not Enough Room for Entry %d < %d",
666                  dwMaxEntryLength, sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t));
667         return CM_ERROR_TOOBIG;
668     }
669
670     if (!name)
671         name = L"";
672     if (!shortName)
673         shortName = L"";
674
675     dwEntryLength = sizeof(AFSDirEnumEntry);
676
677     /* Populate the error code */
678     smb_MapNTError(cmError, &pCurrentEntry->NTStatus, TRUE);
679
680     /* Populate the fake data */
681     pCurrentEntry->FileId.Cell = fidp->cell;
682     pCurrentEntry->FileId.Volume = fidp->volume;
683     pCurrentEntry->FileId.Vnode = fidp->vnode;
684     pCurrentEntry->FileId.Unique = fidp->unique;
685     pCurrentEntry->FileId.Hash = fidp->hash;
686
687     pCurrentEntry->FileType = CM_SCACHETYPE_UNKNOWN;
688
689     pCurrentEntry->DataVersion.QuadPart = CM_SCACHE_VERSION_BAD;
690
691     cm_LargeSearchTimeFromUnixTime(&ft, 0);
692     pCurrentEntry->Expiration.LowPart = ft.dwLowDateTime;
693     pCurrentEntry->Expiration.HighPart = ft.dwHighDateTime;
694
695     cm_LargeSearchTimeFromUnixTime(&ft, 0);
696     pCurrentEntry->CreationTime.LowPart = ft.dwLowDateTime;
697     pCurrentEntry->CreationTime.HighPart = ft.dwHighDateTime;
698     pCurrentEntry->LastAccessTime = pCurrentEntry->CreationTime;
699     pCurrentEntry->LastWriteTime = pCurrentEntry->CreationTime;
700     pCurrentEntry->ChangeTime = pCurrentEntry->CreationTime;
701
702     pCurrentEntry->EndOfFile.QuadPart = 0;
703     pCurrentEntry->AllocationSize.QuadPart = 0;
704     pCurrentEntry->FileAttributes = 0;
705     pCurrentEntry->EaSize = 0;
706     pCurrentEntry->Links = 0;
707
708     len = wcslen(shortName);
709     wcsncpy(pCurrentEntry->ShortName, shortName, len);
710     pCurrentEntry->ShortNameLength = (CCHAR)(len * sizeof(WCHAR));
711
712     pCurrentEntry->FileNameOffset = sizeof(AFSDirEnumEntry);
713     len = wcslen(name);
714     wname = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->FileNameOffset);
715     wcsncpy(wname, name, len);
716     pCurrentEntry->FileNameLength = (ULONG)(sizeof(WCHAR) * len);
717
718     pCurrentEntry->TargetNameOffset = 0;
719     pCurrentEntry->TargetNameLength = 0;
720
721     dwEntryLength += pCurrentEntry->FileNameLength + pCurrentEntry->TargetNameLength;
722     dwEntryLength += (dwEntryLength % 8) ? 8 - (dwEntryLength % 8) : 0;   /* quad align */
723     if (ppNextEntry)
724         *ppNextEntry = (AFSDirEnumEntry *)((PBYTE)pCurrentEntry + dwEntryLength);
725     if (pdwRemainingLength)
726         *pdwRemainingLength = dwMaxEntryLength - dwEntryLength;
727
728     osi_Log3(afsd_logp, "RDR_PopulateCurrentEntryNoScp Success FileNameLength=%d TargetNameLength=%d RemainingLength=%d",
729               pCurrentEntry->FileNameLength, pCurrentEntry->TargetNameLength, *pdwRemainingLength);
730
731     return code;
732 }
733
734 void
735 RDR_EnumerateDirectory( IN cm_user_t *userp,
736                         IN AFSFileID DirID,
737                         IN AFSDirQueryCB *QueryCB,
738                         IN BOOL bWow64,
739                         IN BOOL bSkipStatus,
740                         IN DWORD ResultBufferLength,
741                         IN OUT AFSCommResult **ResultCB)
742 {
743     DWORD status;
744     cm_direnum_t *      enump = NULL;
745     AFSDirEnumResp  * pDirEnumResp;
746     AFSDirEnumEntry * pCurrentEntry;
747     size_t size = ResultBufferLength ? sizeof(AFSCommResult) + ResultBufferLength - 1 : sizeof(AFSCommResult);
748     DWORD             dwMaxEntryLength;
749     afs_uint32  code = 0;
750     cm_fid_t      fid;
751     cm_scache_t * dscp = NULL;
752     cm_req_t      req;
753
754     RDR_InitReq(&req, bWow64);
755
756     osi_Log4(afsd_logp, "RDR_EnumerateDirectory FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
757              DirID.Cell, DirID.Volume, DirID.Vnode, DirID.Unique);
758
759     *ResultCB = (AFSCommResult *)malloc(size);
760     if (!(*ResultCB)) {
761         osi_Log0(afsd_logp, "RDR_EnumerateDirectory Out of Memory");
762         return;
763     }
764
765     memset(*ResultCB, 0, size);
766
767     if (QueryCB->EnumHandle == (ULONG_PTR)-1) {
768         osi_Log0(afsd_logp, "RDR_EnumerateDirectory No More Entries");
769         (*ResultCB)->ResultStatus = STATUS_NO_MORE_ENTRIES;
770         (*ResultCB)->ResultBufferLength = 0;
771         return;
772     }
773
774     (*ResultCB)->ResultBufferLength = dwMaxEntryLength = ResultBufferLength;
775     if (ResultBufferLength) {
776         pDirEnumResp = (AFSDirEnumResp *)&(*ResultCB)->ResultData;
777         pCurrentEntry = (AFSDirEnumEntry *)&pDirEnumResp->Entry;
778         dwMaxEntryLength -= FIELD_OFFSET( AFSDirEnumResp, Entry);      /* AFSDirEnumResp */
779     }
780
781     if (DirID.Cell != 0) {
782         fid.cell   = DirID.Cell;
783         fid.volume = DirID.Volume;
784         fid.vnode  = DirID.Vnode;
785         fid.unique = DirID.Unique;
786         fid.hash   = DirID.Hash;
787
788         code = cm_GetSCache(&fid, NULL, &dscp, userp, &req);
789         if (code) {
790             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
791             (*ResultCB)->ResultStatus = status;
792             osi_Log2(afsd_logp, "RDR_EnumerateDirectory cm_GetSCache failure code=0x%x status=0x%x",
793                       code, status);
794             return;
795         }
796     } else {
797         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
798         osi_Log0(afsd_logp, "RDR_EnumerateDirectory Object Name Invalid - Cell = 0");
799         return;
800     }
801
802     /* get the directory size */
803     lock_ObtainWrite(&dscp->rw);
804     code = cm_SyncOp(dscp, NULL, userp, &req, PRSFS_LOOKUP,
805                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
806     if (code) {
807         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
808         (*ResultCB)->ResultStatus = status;
809         lock_ReleaseWrite(&dscp->rw);
810         cm_ReleaseSCache(dscp);
811         osi_Log2(afsd_logp, "RDR_EnumerateDirectory cm_SyncOp failure code=0x%x status=0x%x",
812                   code, status);
813         return;
814     }
815
816     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
817     lock_ReleaseWrite(&dscp->rw);
818
819     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
820         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
821         cm_ReleaseSCache(dscp);
822         osi_Log1(afsd_logp, "RDR_EnumerateDirectory Not a Directory dscp=0x%p",
823                  dscp);
824         return;
825     }
826
827     osi_Log1(afsd_logp, "RDR_EnumerateDirectory dv=%u", (afs_uint32)dscp->dataVersion);
828
829     /*
830      * If there is no enumeration handle, then this is a new query
831      * and we must perform an enumeration for the specified object.
832      */
833     if (QueryCB->EnumHandle == (ULONG_PTR)NULL) {
834         cm_dirOp_t    dirop;
835
836         code = cm_BeginDirOp(dscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
837         if (code == 0) {
838             code = cm_BPlusDirEnumerate(dscp, userp, &req,
839                                         TRUE /* dir locked */, NULL /* no mask */,
840                                         TRUE /* fetch status? */, &enump);
841             if (code) {
842                 osi_Log1(afsd_logp, "RDR_EnumerateDirectory cm_BPlusDirEnumerate failure code=0x%x",
843                           code);
844             }
845             cm_EndDirOp(&dirop);
846         } else {
847             osi_Log1(afsd_logp, "RDR_EnumerateDirectory cm_BeginDirOp failure code=0x%x",
848                       code);
849         }
850     } else {
851         enump = (cm_direnum_t *)QueryCB->EnumHandle;
852     }
853
854     if (enump) {
855         if (ResultBufferLength == 0) {
856             code = cm_BPlusDirEnumBulkStat(enump);
857             if (code) {
858                 osi_Log1(afsd_logp, "RDR_EnumerateDirectory cm_BPlusDirEnumBulkStat failure code=0x%x",
859                           code);
860             }
861         } else {
862             cm_direnum_entry_t * entryp = NULL;
863
864             pDirEnumResp->SnapshotDataVersion.QuadPart = enump->dataVersion;
865
866           getnextentry:
867             if (dwMaxEntryLength < sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t)) {
868                 osi_Log0(afsd_logp, "RDR_EnumerateDirectory out of space, returning");
869                 goto outofspace;
870             }
871
872             code = cm_BPlusDirNextEnumEntry(enump, &entryp);
873
874             if ((code == 0 || code == CM_ERROR_STOPNOW) && entryp) {
875                 cm_scache_t *scp = NULL;
876                 int stopnow = (code == CM_ERROR_STOPNOW);
877
878                 if ( !wcscmp(L".", entryp->name) || !wcscmp(L"..", entryp->name) ) {
879                     osi_Log0(afsd_logp, "RDR_EnumerateDirectory skipping . or ..");
880                     if (stopnow)
881                         goto outofspace;
882                     goto getnextentry;
883                 }
884
885                 if (bSkipStatus) {
886                     code = cm_GetSCache(&entryp->fid, &dscp->fid, &scp, userp, &req);
887                     if (code) {
888                         osi_Log5(afsd_logp, "RDR_EnumerateDirectory cm_GetSCache failure cell %u vol %u vnode %u uniq %u code=0x%x",
889                                  entryp->fid.cell, entryp->fid.volume, entryp->fid.vnode, entryp->fid.unique, code);
890                     }
891                 } else {
892                     code = entryp->errorCode;
893                     scp = code ? NULL : cm_FindSCache(&entryp->fid);
894                 }
895
896                 if (scp) {
897                     code = RDR_PopulateCurrentEntry( pCurrentEntry, dwMaxEntryLength,
898                                                      dscp, scp, userp, &req,
899                                                      entryp->name,
900                                                      cm_shortNames && cm_Is8Dot3(entryp->name) ? NULL : entryp->shortName,
901                                                      (bWow64 ? RDR_POP_WOW64 : 0) |
902                                                      (bSkipStatus ? RDR_POP_NO_GETSTATUS : 0),
903                                                      code,
904                                                      &pCurrentEntry, &dwMaxEntryLength);
905                     cm_ReleaseSCache(scp);
906                 } else {
907                     code = RDR_PopulateCurrentEntryNoScp( pCurrentEntry, dwMaxEntryLength,
908                                                           dscp, &entryp->fid, userp, &req,
909                                                           entryp->name,
910                                                           cm_shortNames && cm_Is8Dot3(entryp->name) ? NULL : entryp->shortName,
911                                                           (bWow64 ? RDR_POP_WOW64 : 0),
912                                                           code,
913                                                           &pCurrentEntry, &dwMaxEntryLength);
914                 }
915                 if (stopnow)
916                     goto outofspace;
917                 goto getnextentry;
918             }
919         }
920     }
921
922   outofspace:
923
924     if (code || enump->next == enump->count || ResultBufferLength == 0) {
925         cm_BPlusDirFreeEnumeration(enump);
926         enump = (cm_direnum_t *)(ULONG_PTR)-1;
927     }
928
929     if (code == 0 || code == CM_ERROR_STOPNOW) {
930         (*ResultCB)->ResultStatus = STATUS_SUCCESS;
931         osi_Log0(afsd_logp, "RDR_EnumerateDirectory SUCCESS");
932     } else {
933         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
934         (*ResultCB)->ResultStatus = status;
935         osi_Log2(afsd_logp, "RDR_EnumerateDirectory Failure code=0x%x status=0x%x",
936                   code, status);
937     }
938
939     if (ResultBufferLength) {
940         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwMaxEntryLength;
941
942         pDirEnumResp->EnumHandle = (ULONG_PTR) enump;
943         pDirEnumResp->CurrentDataVersion.QuadPart = dscp->dataVersion;
944     }
945
946     if (dscp)
947         cm_ReleaseSCache(dscp);
948
949     return;
950 }
951
952 void
953 RDR_EvaluateNodeByName( IN cm_user_t *userp,
954                         IN AFSFileID ParentID,
955                         IN WCHAR   *FileNameCounted,
956                         IN DWORD    FileNameLength,
957                         IN BOOL     CaseSensitive,
958                         IN BOOL     bWow64,
959                         IN BOOL     bHoldFid,
960                         IN BOOL     bNoFollow,
961                         IN DWORD    ResultBufferLength,
962                         IN OUT AFSCommResult **ResultCB)
963 {
964     AFSFileEvalResultCB *pEvalResultCB = NULL;
965     AFSDirEnumEntry * pCurrentEntry;
966     size_t size = ResultBufferLength ? sizeof(AFSCommResult) + ResultBufferLength - 1 : sizeof(AFSCommResult);
967     afs_uint32  code = 0;
968     cm_scache_t * scp = NULL;
969     cm_scache_t * dscp = NULL;
970     cm_req_t      req;
971     cm_fid_t      parentFid;
972     DWORD         status;
973     DWORD         dwRemaining;
974     WCHAR       * wszName = NULL;
975     size_t        cbName;
976     BOOL          bVol = FALSE;
977     wchar_t       FileName[260];
978
979     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
980
981     RDR_InitReq(&req, bWow64);
982
983     osi_Log4(afsd_logp, "RDR_EvaluateNodeByName parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
984              ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
985
986     /* Allocate enough room to add a volume prefix if necessary */
987     cbName = FileNameLength + (CM_PREFIX_VOL_CCH + 1) * sizeof(WCHAR);
988     wszName = malloc(cbName);
989     if (!wszName) {
990         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName Out of Memory");
991         return;
992     }
993     StringCbCopyNW(wszName, cbName, FileName, FileNameLength);
994     osi_Log1(afsd_logp, "... name=%S", osi_LogSaveStringW(afsd_logp, wszName));
995
996     *ResultCB = (AFSCommResult *)malloc(size);
997     if (!(*ResultCB)) {
998         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName Out of Memory");
999         free(wszName);
1000         return;
1001     }
1002
1003     memset(*ResultCB, 0, size);
1004     (*ResultCB)->ResultBufferLength = 0;
1005     dwRemaining = ResultBufferLength;
1006     if (ResultBufferLength >= sizeof( AFSFileEvalResultCB)) {
1007         pEvalResultCB = (AFSFileEvalResultCB *)&(*ResultCB)->ResultData;
1008         pCurrentEntry = &pEvalResultCB->DirEnum;
1009         dwRemaining -= (sizeof( AFSFileEvalResultCB) - sizeof( AFSDirEnumEntry));
1010     }
1011
1012     if (ParentID.Cell != 0) {
1013         parentFid.cell   = ParentID.Cell;
1014         parentFid.volume = ParentID.Volume;
1015         parentFid.vnode  = ParentID.Vnode;
1016         parentFid.unique = ParentID.Unique;
1017         parentFid.hash   = ParentID.Hash;
1018
1019         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1020         if (code) {
1021             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1022             (*ResultCB)->ResultStatus = status;
1023             if ( status == STATUS_INVALID_HANDLE)
1024                 status = STATUS_OBJECT_PATH_INVALID;
1025             osi_Log2(afsd_logp, "RDR_EvaluateNodeByName cm_GetSCache parentFID failure code=0x%x status=0x%x",
1026                       code, status);
1027             free(wszName);
1028             return;
1029         }
1030     } else {
1031         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
1032         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName Object Name Invalid - Cell = 0");
1033         return;
1034     }
1035
1036     /* get the directory size */
1037     lock_ObtainWrite(&dscp->rw);
1038     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1039                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1040     if (code) {
1041         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1042         (*ResultCB)->ResultStatus = status;
1043         lock_ReleaseWrite(&dscp->rw);
1044         cm_ReleaseSCache(dscp);
1045         osi_Log3(afsd_logp, "RDR_EvaluateNodeByName cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1046                  dscp, code, status);
1047         free(wszName);
1048         return;
1049     }
1050     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1051     lock_ReleaseWrite(&dscp->rw);
1052
1053     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1054         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1055         cm_ReleaseSCache(dscp);
1056         osi_Log1(afsd_logp, "RDR_EvaluateNodeByName Not a Directory dscp=0x%p",
1057                  dscp);
1058         free(wszName);
1059         return;
1060     }
1061
1062     code = cm_Lookup(dscp, wszName, CM_FLAG_CHECKPATH, userp, &req, &scp);
1063
1064     if ((code == CM_ERROR_NOSUCHPATH || code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH) &&
1065          (wcschr(wszName, '%') != NULL || wcschr(wszName, '#') != NULL)) {
1066         /*
1067          * A volume reference:  <cell>{%,#}<volume> -> @vol:<cell>{%,#}<volume>
1068          */
1069         StringCchCopyNW(wszName, cbName, _C(CM_PREFIX_VOL), CM_PREFIX_VOL_CCH);
1070         StringCbCatNW(wszName, cbName, FileName, FileNameLength);
1071         bVol = TRUE;
1072
1073         code = cm_EvaluateVolumeReference(wszName, CM_FLAG_CHECKPATH, userp, &req, &scp);
1074     }
1075
1076     if (code == 0 && scp) {
1077         wchar_t shortName[13]=L"";
1078
1079         if (!cm_shortNames) {
1080             shortName[0] = L'\0';
1081         } else if (bVol) {
1082             cm_Gen8Dot3VolNameW(scp->fid.cell, scp->fid.volume, shortName, NULL);
1083         } else if (!cm_Is8Dot3(wszName)) {
1084             cm_dirFid_t dfid;
1085
1086             dfid.vnode = htonl(scp->fid.vnode);
1087             dfid.unique = htonl(scp->fid.unique);
1088
1089             cm_Gen8Dot3NameIntW(FileName, &dfid, shortName, NULL);
1090         } else {
1091             shortName[0] = L'\0';
1092         }
1093
1094         code = RDR_PopulateCurrentEntry(pCurrentEntry, dwRemaining,
1095                                         dscp, scp, userp, &req,
1096                                         FileName, shortName,
1097                                         (bWow64 ? RDR_POP_WOW64 : 0) |
1098                                         (bNoFollow ? 0 : (RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS)),
1099                                         0, NULL, &dwRemaining);
1100         if (bHoldFid)
1101             RDR_FlagScpInUse( scp, FALSE );
1102         cm_ReleaseSCache(scp);
1103
1104         if (code) {
1105             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1106             (*ResultCB)->ResultStatus = status;
1107             osi_Log2(afsd_logp, "RDR_EvaluateNodeByName FAILURE code=0x%x status=0x%x",
1108                       code, status);
1109         } else {
1110             pEvalResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1111             (*ResultCB)->ResultStatus = STATUS_SUCCESS;
1112             (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1113             osi_Log0(afsd_logp, "RDR_EvaluateNodeByName SUCCESS");
1114         }
1115     } else if (code) {
1116         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1117         (*ResultCB)->ResultStatus = status;
1118         osi_Log2(afsd_logp, "RDR_EvaluateNodeByName FAILURE code=0x%x status=0x%x",
1119                  code, status);
1120     } else {
1121         (*ResultCB)->ResultStatus = STATUS_NO_SUCH_FILE;
1122         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName No Such File");
1123     }
1124     cm_ReleaseSCache(dscp);
1125     free(wszName);
1126
1127     return;
1128 }
1129
1130 void
1131 RDR_EvaluateNodeByID( IN cm_user_t *userp,
1132                       IN AFSFileID ParentID,            /* not used */
1133                       IN AFSFileID SourceID,
1134                       IN BOOL      bWow64,
1135                       IN BOOL      bNoFollow,
1136                       IN BOOL      bHoldFid,
1137                       IN DWORD     ResultBufferLength,
1138                       IN OUT AFSCommResult **ResultCB)
1139 {
1140     AFSFileEvalResultCB *pEvalResultCB = NULL;
1141     AFSDirEnumEntry * pCurrentEntry = NULL;
1142     size_t size = ResultBufferLength ? sizeof(AFSCommResult) + ResultBufferLength - 1 : sizeof(AFSCommResult);
1143     afs_uint32  code = 0;
1144     cm_scache_t * scp = NULL;
1145     cm_scache_t * dscp = NULL;
1146     cm_req_t      req;
1147     cm_fid_t      Fid;
1148     cm_fid_t      parentFid;
1149     DWORD         status;
1150     DWORD         dwRemaining;
1151
1152     osi_Log4(afsd_logp, "RDR_EvaluateNodeByID source FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1153               SourceID.Cell, SourceID.Volume, SourceID.Vnode, SourceID.Unique);
1154     osi_Log4(afsd_logp, "... parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1155               ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
1156
1157     *ResultCB = (AFSCommResult *)malloc(size);
1158     if (!(*ResultCB)) {
1159         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Out of Memory");
1160         return;
1161     }
1162
1163     memset(*ResultCB, 0, size);
1164     (*ResultCB)->ResultBufferLength = 0;
1165     dwRemaining = ResultBufferLength;
1166     if (ResultBufferLength >= sizeof( AFSFileEvalResultCB)) {
1167         pEvalResultCB = (AFSFileEvalResultCB *)&(*ResultCB)->ResultData;
1168         pCurrentEntry = &pEvalResultCB->DirEnum;
1169         dwRemaining -= (sizeof( AFSFileEvalResultCB) - sizeof( AFSDirEnumEntry));
1170     }
1171
1172     RDR_InitReq(&req, bWow64);
1173
1174     if (SourceID.Cell != 0) {
1175         cm_SetFid(&Fid, SourceID.Cell, SourceID.Volume, SourceID.Vnode, SourceID.Unique);
1176         code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
1177         if (code) {
1178             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1179             (*ResultCB)->ResultStatus = status;
1180             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache SourceFID failure code=0x%x status=0x%x",
1181                       code, status);
1182             return;
1183         }
1184     } else {
1185         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
1186         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Object Name Invalid - Cell = 0");
1187         return;
1188     }
1189
1190     if (ParentID.Cell != 0) {
1191         cm_SetFid(&parentFid, ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
1192         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1193         if (code) {
1194             cm_ReleaseSCache(scp);
1195             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1196             if ( status == STATUS_INVALID_HANDLE)
1197                 status = STATUS_OBJECT_PATH_INVALID;
1198             (*ResultCB)->ResultStatus = status;
1199             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache parentFID failure code=0x%x status=0x%x",
1200                       code, status);
1201             return;
1202         }
1203     } else if (SourceID.Vnode == 1) {
1204         dscp = scp;
1205         cm_HoldSCache(dscp);
1206     } else if (scp->parentVnode) {
1207         cm_SetFid(&parentFid, SourceID.Cell, SourceID.Volume, scp->parentVnode, scp->parentUnique);
1208         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1209         if (code) {
1210             cm_ReleaseSCache(scp);
1211             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1212             if ( status == STATUS_INVALID_HANDLE)
1213                 status = STATUS_OBJECT_PATH_INVALID;
1214             (*ResultCB)->ResultStatus = status;
1215             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache parentFID failure code=0x%x status=0x%x",
1216                       code, status);
1217             return;
1218         }
1219     } else {
1220         (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
1221         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Object Path Invalid - Unknown Parent");
1222         return;
1223     }
1224
1225     /* Make sure the directory is current */
1226     lock_ObtainWrite(&dscp->rw);
1227     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1228                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1229     if (code) {
1230         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1231         (*ResultCB)->ResultStatus = status;
1232         lock_ReleaseWrite(&dscp->rw);
1233         cm_ReleaseSCache(dscp);
1234         cm_ReleaseSCache(scp);
1235         osi_Log3(afsd_logp, "RDR_EvaluateNodeByID cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1236                  dscp, code, status);
1237         return;
1238     }
1239
1240     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1241     lock_ReleaseWrite(&dscp->rw);
1242
1243     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1244         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1245         cm_ReleaseSCache(dscp);
1246         cm_ReleaseSCache(scp);
1247         osi_Log1(afsd_logp, "RDR_EvaluateNodeByID Not a Directory dscp=0x%p", dscp);
1248         return;
1249     }
1250
1251     code = RDR_PopulateCurrentEntry(pCurrentEntry, dwRemaining,
1252                                     dscp, scp, userp, &req, NULL, NULL,
1253                                     (bWow64 ? RDR_POP_WOW64 : 0) |
1254                                     (bNoFollow ? 0 : (RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS)),
1255                                     0, NULL, &dwRemaining);
1256
1257     if (bHoldFid)
1258         RDR_FlagScpInUse( scp, FALSE );
1259     cm_ReleaseSCache(scp);
1260     cm_ReleaseSCache(dscp);
1261
1262     if (code) {
1263         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1264         (*ResultCB)->ResultStatus = status;
1265         osi_Log2(afsd_logp, "RDR_EvaluateNodeByID FAILURE code=0x%x status=0x%x",
1266                  code, status);
1267     } else {
1268         pEvalResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1269
1270         (*ResultCB)->ResultStatus = STATUS_SUCCESS;
1271         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1272         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID SUCCESS");
1273     }
1274     return;
1275 }
1276
1277 void
1278 RDR_CreateFileEntry( IN cm_user_t *userp,
1279                      IN WCHAR *FileNameCounted,
1280                      IN DWORD FileNameLength,
1281                      IN AFSFileCreateCB *CreateCB,
1282                      IN BOOL bWow64,
1283                      IN BOOL bHoldFid,
1284                      IN DWORD ResultBufferLength,
1285                      IN OUT AFSCommResult **ResultCB)
1286 {
1287     AFSFileCreateResultCB *pResultCB = NULL;
1288     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1289     cm_fid_t            parentFid;
1290     afs_uint32          code;
1291     cm_scache_t *       dscp = NULL;
1292     afs_uint32          flags = 0;
1293     cm_attr_t           setAttr;
1294     cm_scache_t *       scp = NULL;
1295     cm_req_t            req;
1296     DWORD               status;
1297     wchar_t             FileName[260];
1298
1299     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
1300
1301     osi_Log4(afsd_logp, "RDR_CreateFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1302               CreateCB->ParentId.Cell, CreateCB->ParentId.Volume,
1303               CreateCB->ParentId.Vnode, CreateCB->ParentId.Unique);
1304     osi_Log1(afsd_logp, "... name=%S", osi_LogSaveStringW(afsd_logp, FileName));
1305
1306     RDR_InitReq(&req, bWow64);
1307     memset(&setAttr, 0, sizeof(cm_attr_t));
1308
1309     *ResultCB = (AFSCommResult *)malloc(size);
1310     if (!(*ResultCB)) {
1311         osi_Log0(afsd_logp, "RDR_CreateFileEntry out of memory");
1312         return;
1313     }
1314
1315     memset( *ResultCB,
1316             '\0',
1317             size);
1318
1319     parentFid.cell   = CreateCB->ParentId.Cell;
1320     parentFid.volume = CreateCB->ParentId.Volume;
1321     parentFid.vnode  = CreateCB->ParentId.Vnode;
1322     parentFid.unique = CreateCB->ParentId.Unique;
1323     parentFid.hash   = CreateCB->ParentId.Hash;
1324
1325     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1326     if (code) {
1327         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1328         (*ResultCB)->ResultStatus = status;
1329         if ( status == STATUS_INVALID_HANDLE)
1330             status = STATUS_OBJECT_PATH_INVALID;
1331         osi_Log2(afsd_logp, "RDR_CreateFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1332                   code, status);
1333         return;
1334     }
1335
1336     lock_ObtainWrite(&dscp->rw);
1337     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1338                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1339     if (code) {
1340         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1341         (*ResultCB)->ResultStatus = status;
1342         lock_ReleaseWrite(&dscp->rw);
1343         cm_ReleaseSCache(dscp);
1344         osi_Log3(afsd_logp, "RDR_CreateFileEntry cm_SyncOp failure (1) dscp=0x%p code=0x%x status=0x%x",
1345                  dscp, code, status);
1346         return;
1347     }
1348
1349     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1350     lock_ReleaseWrite(&dscp->rw);
1351
1352     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1353         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1354         cm_ReleaseSCache(dscp);
1355         osi_Log1(afsd_logp, "RDR_CreateFileEntry Not a Directory dscp=0x%p",
1356                  dscp);
1357         return;
1358     }
1359
1360     /* Use current time */
1361     setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
1362     setAttr.clientModTime = time(NULL);
1363
1364     if (CreateCB->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1365         if (smb_unixModeDefaultDir) {
1366             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1367             setAttr.unixModeBits = smb_unixModeDefaultDir;
1368             if (CreateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)
1369                 setAttr.unixModeBits &= ~0222;          /* disable the write bits */
1370         }
1371
1372         code = cm_MakeDir(dscp, FileName, flags, &setAttr, userp, &req, &scp);
1373     } else {
1374         if (smb_unixModeDefaultFile) {
1375             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1376             setAttr.unixModeBits = smb_unixModeDefaultFile;
1377             if (CreateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)
1378                 setAttr.unixModeBits &= ~0222;          /* disable the write bits */
1379         }
1380
1381         setAttr.mask |= CM_ATTRMASK_LENGTH;
1382         setAttr.length.LowPart = CreateCB->AllocationSize.LowPart;
1383         setAttr.length.HighPart = CreateCB->AllocationSize.HighPart;
1384         code = cm_Create(dscp, FileName, flags, &setAttr, &scp, userp, &req);
1385     }
1386     if (code == 0) {
1387         wchar_t shortName[13]=L"";
1388         cm_dirFid_t dfid;
1389         DWORD dwRemaining;
1390
1391         (*ResultCB)->ResultStatus = 0;  // We will be able to fit all the data in here
1392
1393         (*ResultCB)->ResultBufferLength = sizeof( AFSFileCreateResultCB);
1394
1395         pResultCB = (AFSFileCreateResultCB *)(*ResultCB)->ResultData;
1396
1397         dwRemaining = ResultBufferLength - sizeof( AFSFileCreateResultCB) + sizeof( AFSDirEnumEntry);
1398
1399         lock_ObtainWrite(&dscp->rw);
1400         code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1401                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1402         if (code) {
1403             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1404             (*ResultCB)->ResultStatus = status;
1405             lock_ReleaseWrite(&dscp->rw);
1406             cm_ReleaseSCache(dscp);
1407             cm_ReleaseSCache(scp);
1408             osi_Log3(afsd_logp, "RDR_CreateFileEntry cm_SyncOp failure (2) dscp=0x%p code=0x%x status=0x%x",
1409                       dscp, code, status);
1410             return;
1411         }
1412
1413         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1414
1415         cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1416         lock_ReleaseWrite(&dscp->rw);
1417
1418         if (cm_shortNames) {
1419             dfid.vnode = htonl(scp->fid.vnode);
1420             dfid.unique = htonl(scp->fid.unique);
1421
1422             if (!cm_Is8Dot3(FileName))
1423                 cm_Gen8Dot3NameIntW(FileName, &dfid, shortName, NULL);
1424             else
1425                 shortName[0] = '\0';
1426         }
1427
1428         code = RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
1429                                         dscp, scp, userp, &req, FileName, shortName,
1430                                         RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
1431                                         0, NULL, &dwRemaining);
1432
1433         if (bHoldFid)
1434             RDR_FlagScpInUse( scp, FALSE );
1435         cm_ReleaseSCache(scp);
1436         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1437         osi_Log0(afsd_logp, "RDR_CreateFileEntry SUCCESS");
1438     } else {
1439         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1440         (*ResultCB)->ResultStatus = status;
1441         (*ResultCB)->ResultBufferLength = 0;
1442         osi_Log2(afsd_logp, "RDR_CreateFileEntry FAILURE code=0x%x status=0x%x",
1443                   code, status);
1444     }
1445
1446     cm_ReleaseSCache(dscp);
1447
1448     return;
1449 }
1450
1451 void
1452 RDR_UpdateFileEntry( IN cm_user_t *userp,
1453                      IN AFSFileID FileId,
1454                      IN AFSFileUpdateCB *UpdateCB,
1455                      IN BOOL bWow64,
1456                      IN DWORD ResultBufferLength,
1457                      IN OUT AFSCommResult **ResultCB)
1458 {
1459     AFSFileUpdateResultCB *pResultCB = NULL;
1460     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1461     cm_fid_t            Fid;
1462     cm_fid_t            parentFid;
1463     afs_uint32          code;
1464     afs_uint32          flags = 0;
1465     cm_attr_t           setAttr;
1466     cm_scache_t *       scp = NULL;
1467     cm_scache_t *       dscp = NULL;
1468     cm_req_t            req;
1469     time_t              clientModTime;
1470     FILETIME            ft;
1471     DWORD               status;
1472     BOOL                bScpLocked = FALSE;
1473
1474     RDR_InitReq(&req, bWow64);
1475     memset(&setAttr, 0, sizeof(cm_attr_t));
1476
1477     osi_Log4(afsd_logp, "RDR_UpdateFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1478               UpdateCB->ParentId.Cell, UpdateCB->ParentId.Volume,
1479               UpdateCB->ParentId.Vnode, UpdateCB->ParentId.Unique);
1480     osi_Log4(afsd_logp, "... object FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1481               FileId.Cell, FileId.Volume,
1482               FileId.Vnode, FileId.Unique);
1483
1484     *ResultCB = (AFSCommResult *)malloc( size);
1485     if (!(*ResultCB)) {
1486         osi_Log0(afsd_logp, "RDR_UpdateFileEntry Out of Memory");
1487         return;
1488     }
1489
1490     memset( *ResultCB,
1491             '\0',
1492             size);
1493
1494     parentFid.cell   = UpdateCB->ParentId.Cell;
1495     parentFid.volume = UpdateCB->ParentId.Volume;
1496     parentFid.vnode  = UpdateCB->ParentId.Vnode;
1497     parentFid.unique = UpdateCB->ParentId.Unique;
1498     parentFid.hash   = UpdateCB->ParentId.Hash;
1499
1500     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1501     if (code) {
1502         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1503         (*ResultCB)->ResultStatus = status;
1504         if ( status == STATUS_INVALID_HANDLE)
1505             status = STATUS_OBJECT_PATH_INVALID;
1506         osi_Log2(afsd_logp, "RDR_UpdateFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1507                   code, status);
1508         return;
1509     }
1510
1511     lock_ObtainWrite(&dscp->rw);
1512     bScpLocked = TRUE;
1513     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1514                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1515     if (code) {
1516         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1517         (*ResultCB)->ResultStatus = status;
1518         lock_ReleaseWrite(&dscp->rw);
1519         cm_ReleaseSCache(dscp);
1520         osi_Log3(afsd_logp, "RDR_UpdateFileEntry cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1521                  dscp, code, status);
1522         return;
1523     }
1524
1525     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1526     lock_ReleaseWrite(&dscp->rw);
1527     bScpLocked = FALSE;
1528
1529     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1530         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1531         cm_ReleaseSCache(dscp);
1532         osi_Log1(afsd_logp, "RDR_UpdateFileEntry Not a Directory dscp=0x%p",
1533                  dscp);
1534         return;
1535     }
1536
1537     Fid.cell   = FileId.Cell;
1538     Fid.volume = FileId.Volume;
1539     Fid.vnode  = FileId.Vnode;
1540     Fid.unique = FileId.Unique;
1541     Fid.hash   = FileId.Hash;
1542
1543     code = cm_GetSCache(&Fid, &dscp->fid, &scp, userp, &req);
1544     if (code) {
1545         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1546         (*ResultCB)->ResultStatus = status;
1547         cm_ReleaseSCache(dscp);
1548         osi_Log2(afsd_logp, "RDR_UpdateFileEntry cm_GetSCache object FID failure code=0x%x status=0x%x",
1549                   code, status);
1550         return;
1551     }
1552
1553     lock_ObtainWrite(&scp->rw);
1554     bScpLocked = TRUE;
1555     code = cm_SyncOp(scp, NULL, userp, &req, 0,
1556                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1557     if (code) {
1558         lock_ReleaseWrite(&scp->rw);
1559         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1560         (*ResultCB)->ResultStatus = status;
1561         (*ResultCB)->ResultBufferLength = 0;
1562         cm_ReleaseSCache(dscp);
1563         cm_ReleaseSCache(scp);
1564         osi_Log3(afsd_logp, "RDR_UpdateFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
1565                  scp, code, status);
1566         return;
1567     }
1568     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1569
1570     if (UpdateCB->ChangeTime.QuadPart) {
1571
1572         if (scp->fileType == CM_SCACHETYPE_FILE) {
1573             /* Do not set length and other attributes at the same time */
1574             if (scp->length.QuadPart != UpdateCB->AllocationSize.QuadPart) {
1575                 osi_Log2(afsd_logp, "RDR_UpdateFileEntry Length Change 0x%x -> 0x%x",
1576                           (afs_uint32)scp->length.QuadPart, (afs_uint32)UpdateCB->AllocationSize.QuadPart);
1577                 setAttr.mask |= CM_ATTRMASK_LENGTH;
1578                 setAttr.length.LowPart = UpdateCB->AllocationSize.LowPart;
1579                 setAttr.length.HighPart = UpdateCB->AllocationSize.HighPart;
1580                 lock_ReleaseWrite(&scp->rw);
1581                 bScpLocked = FALSE;
1582                 code = cm_SetAttr(scp, &setAttr, userp, &req);
1583                 if (code)
1584                     goto on_error;
1585                 setAttr.mask = 0;
1586             }
1587         }
1588
1589         if (!bScpLocked) {
1590             lock_ObtainWrite(&scp->rw);
1591             bScpLocked = TRUE;
1592         }
1593         if ((scp->unixModeBits & 0200) && (UpdateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1594             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1595             setAttr.unixModeBits = scp->unixModeBits & ~0222;
1596         } else if (!(scp->unixModeBits & 0200) && !(UpdateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1597             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1598             setAttr.unixModeBits = scp->unixModeBits | 0222;
1599         }
1600     }
1601
1602     if (UpdateCB->LastWriteTime.QuadPart) {
1603         ft.dwLowDateTime = UpdateCB->LastWriteTime.LowPart;
1604         ft.dwHighDateTime = UpdateCB->LastWriteTime.HighPart;
1605
1606         cm_UnixTimeFromLargeSearchTime(& clientModTime, &ft);
1607
1608         if (!bScpLocked) {
1609             lock_ObtainWrite(&scp->rw);
1610             bScpLocked = TRUE;
1611         }
1612         if (scp->clientModTime != clientModTime) {
1613             setAttr.mask |= CM_ATTRMASK_CLIENTMODTIME;
1614             setAttr.clientModTime = clientModTime;
1615         }
1616
1617         /* call setattr */
1618         if (setAttr.mask) {
1619             lock_ReleaseWrite(&scp->rw);
1620             bScpLocked = FALSE;
1621             code = cm_SetAttr(scp, &setAttr, userp, &req);
1622         } else
1623             code = 0;
1624     }
1625
1626   on_error:
1627     if (bScpLocked) {
1628         lock_ReleaseWrite(&scp->rw);
1629     }
1630
1631     if (code == 0) {
1632         DWORD dwRemaining = ResultBufferLength - sizeof( AFSFileUpdateResultCB) + sizeof( AFSDirEnumEntry);
1633
1634         pResultCB = (AFSFileUpdateResultCB *)(*ResultCB)->ResultData;
1635
1636         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1637
1638         code = RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
1639                                         dscp, scp, userp, &req, NULL, NULL,
1640                                         RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
1641                                         0, NULL, &dwRemaining);
1642         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1643         osi_Log0(afsd_logp, "RDR_UpdateFileEntry SUCCESS");
1644     } else {
1645         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1646         (*ResultCB)->ResultStatus = status;
1647         (*ResultCB)->ResultBufferLength = 0;
1648         osi_Log2(afsd_logp, "RDR_UpdateFileEntry FAILURE code=0x%x status=0x%x",
1649                   code, status);
1650     }
1651     cm_ReleaseSCache(scp);
1652     cm_ReleaseSCache(dscp);
1653
1654     return;
1655 }
1656
1657 void
1658 RDR_CleanupFileEntry( IN cm_user_t *userp,
1659                       IN AFSFileID FileId,
1660                       IN WCHAR *FileNameCounted,
1661                       IN DWORD FileNameLength,
1662                       IN AFSFileCleanupCB *CleanupCB,
1663                       IN BOOL bWow64,
1664                       IN BOOL bLastHandle,
1665                       IN BOOL bDeleteFile,
1666                       IN BOOL bUnlockFile,
1667                       IN DWORD ResultBufferLength,
1668                       IN OUT AFSCommResult **ResultCB)
1669 {
1670     AFSFileCleanupResultCB *pResultCB = NULL;
1671     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1672     cm_fid_t            Fid;
1673     cm_fid_t            parentFid;
1674     afs_uint32          code = 0;
1675     afs_uint32          flags = 0;
1676     cm_attr_t           setAttr;
1677     cm_scache_t *       scp = NULL;
1678     cm_scache_t *       dscp = NULL;
1679     cm_req_t            req;
1680     time_t              clientModTime;
1681     FILETIME            ft;
1682     DWORD               status;
1683     BOOL                bScpLocked = FALSE;
1684     BOOL                bDscpLocked = FALSE;
1685     BOOL                bFlushFile = FALSE;
1686     cm_key_t            key;
1687
1688     RDR_InitReq(&req, bWow64);
1689     memset(&setAttr, 0, sizeof(cm_attr_t));
1690
1691     osi_Log4(afsd_logp, "RDR_CleanupFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1692               CleanupCB->ParentId.Cell, CleanupCB->ParentId.Volume,
1693               CleanupCB->ParentId.Vnode, CleanupCB->ParentId.Unique);
1694     osi_Log4(afsd_logp, "... object FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1695               FileId.Cell, FileId.Volume,
1696               FileId.Vnode, FileId.Unique);
1697
1698     *ResultCB = (AFSCommResult *)malloc( size);
1699     if (!(*ResultCB)) {
1700         osi_Log0(afsd_logp, "RDR_CleanupFileEntry Out of Memory");
1701         return;
1702     }
1703
1704     memset( *ResultCB,
1705             '\0',
1706             size);
1707
1708     parentFid.cell   = CleanupCB->ParentId.Cell;
1709     parentFid.volume = CleanupCB->ParentId.Volume;
1710     parentFid.vnode  = CleanupCB->ParentId.Vnode;
1711     parentFid.unique = CleanupCB->ParentId.Unique;
1712     parentFid.hash   = CleanupCB->ParentId.Hash;
1713
1714     if (parentFid.cell) {
1715         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1716         if (code) {
1717             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1718             if ( status == STATUS_INVALID_HANDLE)
1719                 status = STATUS_OBJECT_PATH_INVALID;
1720             (*ResultCB)->ResultStatus = status;
1721             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1722                      code, status);
1723             return;
1724         }
1725
1726         lock_ObtainWrite(&dscp->rw);
1727         bDscpLocked = TRUE;
1728         code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1729                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1730         if (code) {
1731             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp failure dscp=0x%p code=0x%x",
1732                     dscp, code);
1733             if (code)
1734                 goto on_error;
1735         }
1736
1737         cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1738         lock_ReleaseWrite(&dscp->rw);
1739         bDscpLocked = FALSE;
1740
1741         if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1742             (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1743             cm_ReleaseSCache(dscp);
1744             osi_Log1(afsd_logp, "RDR_CleanupFileEntry Not a Directory dscp=0x%p",
1745                      dscp);
1746             if (code)
1747                 goto on_error;
1748         }
1749     }
1750
1751     Fid.cell   = FileId.Cell;
1752     Fid.volume = FileId.Volume;
1753     Fid.vnode  = FileId.Vnode;
1754     Fid.unique = FileId.Unique;
1755     Fid.hash   = FileId.Hash;
1756
1757     code = cm_GetSCache(&Fid, dscp ? &dscp->fid : NULL, &scp, userp, &req);
1758     if (code) {
1759         osi_Log1(afsd_logp, "RDR_CleanupFileEntry cm_GetSCache object FID failure code=0x%x",
1760                  code);
1761         goto on_error;
1762     }
1763
1764     lock_ObtainWrite(&scp->rw);
1765     bScpLocked = TRUE;
1766     code = cm_SyncOp(scp, NULL, userp, &req, 0,
1767                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1768     if (code) {
1769         osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp failure scp=0x%p code=0x%x",
1770                  scp, code);
1771         goto on_error;
1772     }
1773     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1774
1775     if ((bLastHandle || bFlushFile) &&
1776         scp->redirBufCount > 0)
1777     {
1778         LARGE_INTEGER heldExtents;
1779         AFSFileExtentCB extentList[1024];
1780         DWORD extentCount = 0;
1781         cm_buf_t *srbp;
1782         time_t now;
1783
1784         time(&now);
1785         heldExtents.QuadPart = 0;
1786
1787         for ( srbp = redirq_to_cm_buf_t(scp->redirQueueT);
1788               srbp;
1789               srbp = redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq)))
1790         {
1791             extentList[extentCount].Flags = 0;
1792             extentList[extentCount].Length = cm_data.blockSize;
1793             extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1794             extentList[extentCount].CacheOffset.QuadPart = srbp->datap - RDR_extentBaseAddress;
1795             lock_ObtainWrite(&buf_globalLock);
1796             srbp->redirReleaseRequested = now;
1797             lock_ReleaseWrite(&buf_globalLock);
1798             extentCount++;
1799
1800             if (extentCount == 1024) {
1801                 lock_ReleaseWrite(&scp->rw);
1802                 code = RDR_RequestExtentRelease(&scp->fid, heldExtents, extentCount, extentList);
1803                 if (code) {
1804                     if (code == CM_ERROR_RETRY) {
1805                         /*
1806                          * The redirector either is not holding the extents or cannot let them
1807                          * go because they are otherwise in use.  At the moment, do nothing.
1808                          */
1809                     } else
1810                         break;
1811                 }
1812                 extentCount = 0;
1813                 bFlushFile = TRUE;
1814                 lock_ObtainWrite(&scp->rw);
1815             }
1816         }
1817
1818         if (code == 0 && extentCount > 0) {
1819             if (bScpLocked) {
1820                 lock_ReleaseWrite(&scp->rw);
1821                 bScpLocked = FALSE;
1822             }
1823             code = RDR_RequestExtentRelease(&scp->fid, heldExtents, extentCount, extentList);
1824             bFlushFile = TRUE;
1825         }
1826     }
1827
1828     /* No longer in use by redirector */
1829     if (!bScpLocked) {
1830         lock_ObtainWrite(&scp->rw);
1831         bScpLocked = TRUE;
1832     }
1833
1834     if (bLastHandle) {
1835         lock_AssertWrite(&scp->rw);
1836         scp->flags &= ~CM_SCACHEFLAG_RDR_IN_USE;
1837     }
1838
1839     /* If not a readonly object, flush dirty data and update metadata */
1840     if (!(scp->flags & CM_SCACHEFLAG_RO)) {
1841         if ((bLastHandle || bFlushFile) &&
1842              buf_DirtyBuffersExist(&scp->fid)) {
1843             if (!bScpLocked) {
1844                 lock_ObtainWrite(&scp->rw);
1845                 bScpLocked = TRUE;
1846             }
1847             code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_WRITE,
1848                              CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1849             if (code == 0) {
1850                 if (bScpLocked) {
1851                     lock_ReleaseWrite(&scp->rw);
1852                     bScpLocked = FALSE;
1853                 }
1854
1855                 code = cm_FSync(scp, userp, &req, bScpLocked);
1856             }
1857             if (bLastHandle && code)
1858                 goto unlock;
1859         }
1860
1861         if (CleanupCB->ChangeTime.QuadPart) {
1862
1863             if (scp->fileType == CM_SCACHETYPE_FILE) {
1864                 /* Do not set length and other attributes at the same time */
1865                 if (scp->length.QuadPart != CleanupCB->AllocationSize.QuadPart) {
1866                     osi_Log2(afsd_logp, "RDR_CleanupFileEntry Length Change 0x%x -> 0x%x",
1867                              (afs_uint32)scp->length.QuadPart, (afs_uint32)CleanupCB->AllocationSize.QuadPart);
1868                     setAttr.mask |= CM_ATTRMASK_LENGTH;
1869                     setAttr.length.LowPart = CleanupCB->AllocationSize.LowPart;
1870                     setAttr.length.HighPart = CleanupCB->AllocationSize.HighPart;
1871
1872                     if (bScpLocked) {
1873                         lock_ReleaseWrite(&scp->rw);
1874                         bScpLocked = FALSE;
1875                     }
1876                     code = cm_SetAttr(scp, &setAttr, userp, &req);
1877                     if (code)
1878                         goto unlock;
1879                     setAttr.mask = 0;
1880                 }
1881             }
1882
1883             if (!bScpLocked) {
1884                 lock_ObtainWrite(&scp->rw);
1885                 bScpLocked = TRUE;
1886             }
1887
1888             if ((scp->unixModeBits & 0200) && (CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1889                 setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1890                 setAttr.unixModeBits = scp->unixModeBits & ~0222;
1891             } else if (!(scp->unixModeBits & 0200) && !(CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1892                 setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1893                 setAttr.unixModeBits = scp->unixModeBits | 0222;
1894             }
1895         }
1896
1897         if (CleanupCB->LastWriteTime.QuadPart) {
1898             ft.dwLowDateTime = CleanupCB->LastWriteTime.LowPart;
1899             ft.dwHighDateTime = CleanupCB->LastWriteTime.HighPart;
1900
1901             cm_UnixTimeFromLargeSearchTime(&clientModTime, &ft);
1902             if (scp->clientModTime != clientModTime) {
1903                 setAttr.mask |= CM_ATTRMASK_CLIENTMODTIME;
1904                 setAttr.clientModTime = clientModTime;
1905             }
1906         }
1907
1908         /* call setattr */
1909         if (setAttr.mask) {
1910             lock_ReleaseWrite(&scp->rw);
1911             bScpLocked = FALSE;
1912             code = cm_SetAttr(scp, &setAttr, userp, &req);
1913         } else
1914             code = 0;
1915     }
1916
1917   unlock:
1918     /* Now drop the lock enforcing the share access */
1919     if ( CleanupCB->FileAccess != AFS_FILE_ACCESS_NOLOCK) {
1920         unsigned int sLockType;
1921         LARGE_INTEGER LOffset, LLength;
1922
1923         if (CleanupCB->FileAccess == AFS_FILE_ACCESS_SHARED)
1924             sLockType = LOCKING_ANDX_SHARED_LOCK;
1925         else
1926             sLockType = 0;
1927
1928         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, CleanupCB->Identifier);
1929
1930         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
1931         LOffset.LowPart = SMB_FID_QLOCK_LOW;
1932         LLength.HighPart = 0;
1933         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
1934
1935         if (!bScpLocked) {
1936             lock_ObtainWrite(&scp->rw);
1937             bScpLocked = TRUE;
1938         }
1939
1940         code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
1941         if (code == 0)
1942         {
1943             code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
1944
1945             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
1946
1947             if (code == CM_ERROR_RANGE_NOT_LOCKED)
1948             {
1949                 osi_Log3(afsd_logp, "RDR_CleanupFileEntry Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
1950                          CleanupCB->FileAccess, CleanupCB->ProcessId, CleanupCB->Identifier);
1951
1952             }
1953         }
1954     }
1955
1956     if (bUnlockFile || bDeleteFile) {
1957         if (!bScpLocked) {
1958             lock_ObtainWrite(&scp->rw);
1959             bScpLocked = TRUE;
1960         }
1961         code = cm_SyncOp(scp, NULL, userp, &req, 0,
1962                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
1963         if (code) {
1964             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp (2) failure scp=0x%p code=0x%x",
1965                      scp, code);
1966             goto on_error;
1967         }
1968
1969         key = cm_GenerateKey(CM_SESSION_IFS, CleanupCB->ProcessId, 0);
1970
1971         /* the scp is now locked and current */
1972         code = cm_UnlockByKey(scp, key,
1973                               bDeleteFile ? CM_UNLOCK_FLAG_BY_FID : 0,
1974                               userp, &req);
1975
1976         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
1977
1978         if (code)
1979             goto on_error;
1980     }
1981
1982   on_error:
1983     if (bDscpLocked)
1984         lock_ReleaseWrite(&dscp->rw);
1985     if (bScpLocked)
1986         lock_ReleaseWrite(&scp->rw);
1987
1988     if (code == 0 && dscp && bDeleteFile) {
1989         WCHAR FileName[260];
1990
1991         StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
1992
1993         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
1994             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
1995         else
1996             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
1997     }
1998
1999     if (code == 0) {
2000         if ( ResultBufferLength >=  sizeof( AFSFileCleanupResultCB))
2001         {
2002             (*ResultCB)->ResultBufferLength = sizeof( AFSFileCleanupResultCB);
2003             pResultCB = (AFSFileCleanupResultCB *)&(*ResultCB)->ResultData;
2004             pResultCB->ParentDataVersion.QuadPart = dscp ? dscp->dataVersion : 0;
2005         } else {
2006             (*ResultCB)->ResultBufferLength = 0;
2007         }
2008
2009         (*ResultCB)->ResultStatus = 0;
2010         osi_Log0(afsd_logp, "RDR_CleanupFileEntry SUCCESS");
2011     } else {
2012         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2013         (*ResultCB)->ResultStatus = status;
2014         osi_Log2(afsd_logp, "RDR_CleanupFileEntry FAILURE code=0x%x status=0x%x",
2015                   code, status);
2016     }
2017
2018     if (scp)
2019         cm_ReleaseSCache(scp);
2020     if (dscp)
2021         cm_ReleaseSCache(dscp);
2022
2023     return;
2024 }
2025
2026 void
2027 RDR_DeleteFileEntry( IN cm_user_t *userp,
2028                      IN AFSFileID ParentId,
2029                      IN ULONGLONG ProcessId,
2030                      IN WCHAR *FileNameCounted,
2031                      IN DWORD FileNameLength,
2032                      IN BOOL bWow64,
2033                      IN BOOL bCheckOnly,
2034                      IN DWORD ResultBufferLength,
2035                      IN OUT AFSCommResult **ResultCB)
2036 {
2037
2038     AFSFileDeleteResultCB *pResultCB = NULL;
2039     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2040     cm_fid_t            parentFid;
2041     afs_uint32          code;
2042     cm_scache_t *       dscp = NULL;
2043     cm_scache_t *       scp = NULL;
2044     afs_uint32          flags = 0;
2045     cm_attr_t           setAttr;
2046     cm_req_t            req;
2047     DWORD               status;
2048     wchar_t             FileName[260];
2049     cm_key_t            key;
2050
2051     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
2052
2053     osi_Log4(afsd_logp, "RDR_DeleteFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2054               ParentId.Cell,  ParentId.Volume,
2055               ParentId.Vnode, ParentId.Unique);
2056     osi_Log2(afsd_logp, "... name=%S checkOnly=%x",
2057              osi_LogSaveStringW(afsd_logp, FileName),
2058              bCheckOnly);
2059
2060     RDR_InitReq(&req, bWow64);
2061     memset(&setAttr, 0, sizeof(cm_attr_t));
2062
2063     *ResultCB = (AFSCommResult *)malloc( size);
2064     if (!(*ResultCB)) {
2065         osi_Log0(afsd_logp, "RDR_DeleteFileEntry out of memory");
2066         return;
2067     }
2068
2069     memset( *ResultCB,
2070             '\0',
2071             size);
2072
2073     parentFid.cell   = ParentId.Cell;
2074     parentFid.volume = ParentId.Volume;
2075     parentFid.vnode  = ParentId.Vnode;
2076     parentFid.unique = ParentId.Unique;
2077     parentFid.hash   = ParentId.Hash;
2078
2079     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
2080     if (code) {
2081         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2082         if ( status == STATUS_INVALID_HANDLE)
2083             status = STATUS_OBJECT_PATH_INVALID;
2084         (*ResultCB)->ResultStatus = status;
2085         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
2086                   code, status);
2087         return;
2088     }
2089
2090     lock_ObtainWrite(&dscp->rw);
2091
2092     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
2093                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2094     if (code) {
2095         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2096         (*ResultCB)->ResultStatus = status;
2097         (*ResultCB)->ResultBufferLength = 0;
2098         lock_ReleaseWrite(&dscp->rw);
2099         cm_ReleaseSCache(dscp);
2100         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
2101                  dscp, code, status);
2102         return;
2103     }
2104
2105     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2106     lock_ReleaseWrite(&dscp->rw);
2107
2108     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2109         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2110         cm_ReleaseSCache(dscp);
2111         osi_Log1(afsd_logp, "RDR_DeleteFileEntry Not a Directory dscp=0x%p",
2112                  dscp);
2113         return;
2114     }
2115
2116     code = cm_Lookup(dscp, FileName, 0, userp, &req, &scp);
2117     if (code) {
2118         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2119         (*ResultCB)->ResultStatus = status;
2120         (*ResultCB)->ResultBufferLength = 0;
2121         cm_ReleaseSCache(dscp);
2122         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_Lookup failure code=0x%x status=0x%x",
2123                  code, status);
2124         return;
2125     }
2126
2127     lock_ObtainWrite(&scp->rw);
2128     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_DELETE,
2129                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2130     if (code) {
2131         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2132         (*ResultCB)->ResultStatus = status;
2133         (*ResultCB)->ResultBufferLength = 0;
2134         lock_ReleaseWrite(&scp->rw);
2135         cm_ReleaseSCache(scp);
2136         cm_ReleaseSCache(dscp);
2137         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2138                  scp, code, status);
2139         return;
2140     }
2141
2142     if (!bCheckOnly) {
2143         /* Drop all locks since the file is being deleted */
2144         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2145                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2146         if (code) {
2147             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2148             (*ResultCB)->ResultStatus = status;
2149             (*ResultCB)->ResultBufferLength = 0;
2150             lock_ReleaseWrite(&scp->rw);
2151             cm_ReleaseSCache(scp);
2152             cm_ReleaseSCache(dscp);
2153             osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp Lock failure scp=0x%p code=0x%x status=0x%x",
2154                      scp, code, status);
2155         }
2156
2157         /* the scp is now locked and current */
2158         key = cm_GenerateKey(CM_SESSION_IFS, ProcessId, 0);
2159
2160         code = cm_UnlockByKey(scp, key,
2161                               CM_UNLOCK_FLAG_BY_FID,
2162                               userp, &req);
2163
2164         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2165         lock_ReleaseWrite(&scp->rw);
2166
2167         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
2168             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
2169         else
2170             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
2171     } else {
2172         lock_ReleaseWrite(&scp->rw);
2173     }
2174
2175     if (code == 0) {
2176         (*ResultCB)->ResultStatus = 0;  // We will be able to fit all the data in here
2177
2178         (*ResultCB)->ResultBufferLength = sizeof( AFSFileDeleteResultCB);
2179
2180         pResultCB = (AFSFileDeleteResultCB *)(*ResultCB)->ResultData;
2181
2182         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
2183         osi_Log0(afsd_logp, "RDR_DeleteFileEntry SUCCESS");
2184     } else {
2185         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2186         (*ResultCB)->ResultStatus = status;
2187         (*ResultCB)->ResultBufferLength = 0;
2188         osi_Log2(afsd_logp, "RDR_DeleteFileEntry FAILURE code=0x%x status=0x%x",
2189                   code, status);
2190     }
2191
2192     cm_ReleaseSCache(dscp);
2193     cm_ReleaseSCache(scp);
2194
2195     return;
2196 }
2197
2198 void
2199 RDR_RenameFileEntry( IN cm_user_t *userp,
2200                      IN WCHAR    *SourceFileNameCounted,
2201                      IN DWORD     SourceFileNameLength,
2202                      IN AFSFileID SourceFileId,
2203                      IN AFSFileRenameCB *pRenameCB,
2204                      IN BOOL bWow64,
2205                      IN DWORD ResultBufferLength,
2206                      IN OUT AFSCommResult **ResultCB)
2207 {
2208
2209     AFSFileRenameResultCB *pResultCB = NULL;
2210     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2211     AFSFileID              SourceParentId   = pRenameCB->SourceParentId;
2212     AFSFileID              TargetParentId   = pRenameCB->TargetParentId;
2213     WCHAR *                TargetFileNameCounted = pRenameCB->TargetName;
2214     DWORD                  TargetFileNameLength = pRenameCB->TargetNameLength;
2215     cm_fid_t               SourceParentFid;
2216     cm_fid_t               TargetParentFid;
2217     cm_fid_t               SourceFid;
2218     cm_fid_t               OrigTargetFid = {0,0,0,0,0};
2219     cm_fid_t               TargetFid;
2220     cm_scache_t *          oldDscp;
2221     cm_scache_t *          newDscp;
2222     cm_dirOp_t dirop;
2223     wchar_t                shortName[13];
2224     wchar_t                SourceFileName[260];
2225     wchar_t                TargetFileName[260];
2226     cm_dirFid_t            dfid;
2227     cm_req_t               req;
2228     afs_uint32             code;
2229     DWORD                  status;
2230
2231     RDR_InitReq(&req, bWow64);
2232
2233     StringCchCopyNW(SourceFileName, 260, SourceFileNameCounted, SourceFileNameLength / sizeof(WCHAR));
2234     StringCchCopyNW(TargetFileName, 260, TargetFileNameCounted, TargetFileNameLength / sizeof(WCHAR));
2235
2236     osi_Log4(afsd_logp, "RDR_RenameFileEntry Source Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2237               SourceParentId.Cell,  SourceParentId.Volume,
2238               SourceParentId.Vnode, SourceParentId.Unique);
2239     osi_Log2(afsd_logp, "... Source Name=%S Length %u", osi_LogSaveStringW(afsd_logp, SourceFileName), SourceFileNameLength);
2240     osi_Log4(afsd_logp, "... Target Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2241               TargetParentId.Cell,  TargetParentId.Volume,
2242               TargetParentId.Vnode, TargetParentId.Unique);
2243     osi_Log2(afsd_logp, "... Target Name=%S Length %u", osi_LogSaveStringW(afsd_logp, TargetFileName), TargetFileNameLength);
2244
2245     *ResultCB = (AFSCommResult *)malloc( size);
2246     if (!(*ResultCB))
2247         return;
2248
2249     memset( *ResultCB,
2250             '\0',
2251             size);
2252
2253     pResultCB = (AFSFileRenameResultCB *)(*ResultCB)->ResultData;
2254
2255     if (SourceFileNameLength == 0 || TargetFileNameLength == 0)
2256     {
2257         osi_Log2(afsd_logp, "RDR_RenameFileEntry Invalid Name Length: src %u target %u",
2258                  SourceFileNameLength, TargetFileNameLength);
2259         (*ResultCB)->ResultStatus = STATUS_INVALID_PARAMETER;
2260         return;
2261     }
2262
2263     SourceParentFid.cell   = SourceParentId.Cell;
2264     SourceParentFid.volume = SourceParentId.Volume;
2265     SourceParentFid.vnode  = SourceParentId.Vnode;
2266     SourceParentFid.unique = SourceParentId.Unique;
2267     SourceParentFid.hash   = SourceParentId.Hash;
2268
2269     TargetParentFid.cell   = TargetParentId.Cell;
2270     TargetParentFid.volume = TargetParentId.Volume;
2271     TargetParentFid.vnode  = TargetParentId.Vnode;
2272     TargetParentFid.unique = TargetParentId.Unique;
2273     TargetParentFid.hash   = TargetParentId.Hash;
2274
2275     code = cm_GetSCache(&SourceParentFid, NULL, &oldDscp, userp, &req);
2276     if (code) {
2277         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache source parent failed code 0x%x", code);
2278         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2279         if ( status == STATUS_INVALID_HANDLE)
2280             status = STATUS_OBJECT_PATH_INVALID;
2281         (*ResultCB)->ResultStatus = status;
2282         return;
2283     }
2284
2285     lock_ObtainWrite(&oldDscp->rw);
2286     code = cm_SyncOp(oldDscp, NULL, userp, &req, 0,
2287                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2288     if (code) {
2289         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp oldDscp 0x%p failed code 0x%x", oldDscp, code);
2290         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2291         if ( status == STATUS_INVALID_HANDLE)
2292             status = STATUS_OBJECT_PATH_INVALID;
2293         (*ResultCB)->ResultStatus = status;
2294         lock_ReleaseWrite(&oldDscp->rw);
2295         cm_ReleaseSCache(oldDscp);
2296         return;
2297     }
2298
2299     cm_SyncOpDone(oldDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2300     lock_ReleaseWrite(&oldDscp->rw);
2301
2302
2303     if (oldDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2304         osi_Log1(afsd_logp, "RDR_RenameFileEntry oldDscp 0x%p not a directory", oldDscp);
2305         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2306         cm_ReleaseSCache(oldDscp);
2307         return;
2308     }
2309
2310     code = cm_GetSCache(&TargetParentFid, NULL, &newDscp, userp, &req);
2311     if (code) {
2312         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target parent failed code 0x%x", code);
2313         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2314         (*ResultCB)->ResultStatus = status;
2315         cm_ReleaseSCache(oldDscp);
2316         return;
2317     }
2318
2319     lock_ObtainWrite(&newDscp->rw);
2320     code = cm_SyncOp(newDscp, NULL, userp, &req, 0,
2321                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2322     if (code) {
2323         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp newDscp 0x%p failed code 0x%x", newDscp, code);
2324         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2325         (*ResultCB)->ResultStatus = status;
2326         lock_ReleaseWrite(&newDscp->rw);
2327         cm_ReleaseSCache(oldDscp);
2328         cm_ReleaseSCache(newDscp);
2329         return;
2330     }
2331
2332     cm_SyncOpDone(newDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2333     lock_ReleaseWrite(&newDscp->rw);
2334
2335
2336     if (newDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2337         osi_Log1(afsd_logp, "RDR_RenameFileEntry newDscp 0x%p not a directory", newDscp);
2338         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2339         cm_ReleaseSCache(oldDscp);
2340         cm_ReleaseSCache(newDscp);
2341         return;
2342     }
2343
2344     /* Obtain the original FID just for debugging purposes */
2345     code = cm_BeginDirOp( oldDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2346     if (code == 0) {
2347         code = cm_BPlusDirLookup(&dirop, SourceFileName, &SourceFid);
2348         code = cm_BPlusDirLookup(&dirop, TargetFileName, &OrigTargetFid);
2349         cm_EndDirOp(&dirop);
2350     }
2351
2352     code = cm_Rename( oldDscp, NULL, SourceFileName,
2353                       newDscp, TargetFileName, userp, &req);
2354     if (code == 0) {
2355         cm_scache_t *scp = 0;
2356         DWORD dwRemaining;
2357
2358         (*ResultCB)->ResultBufferLength = ResultBufferLength;
2359         dwRemaining = ResultBufferLength - sizeof( AFSFileRenameResultCB) + sizeof( AFSDirEnumEntry);
2360         (*ResultCB)->ResultStatus = 0;
2361
2362         pResultCB->SourceParentDataVersion.QuadPart = oldDscp->dataVersion;
2363         pResultCB->TargetParentDataVersion.QuadPart = newDscp->dataVersion;
2364
2365         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p SUCCESS",
2366                  oldDscp, newDscp);
2367
2368         code = cm_BeginDirOp( newDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2369         if (code == 0) {
2370             code = cm_BPlusDirLookup(&dirop, TargetFileName, &TargetFid);
2371             cm_EndDirOp(&dirop);
2372         }
2373
2374         if (code != 0) {
2375             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_BPlusDirLookup failed code 0x%x",
2376                      code);
2377             (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
2378             cm_ReleaseSCache(oldDscp);
2379             cm_ReleaseSCache(newDscp);
2380             return;
2381         }
2382
2383         osi_Log4(afsd_logp, "RDR_RenameFileEntry Target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2384                   TargetFid.cell,  TargetFid.volume,
2385                   TargetFid.vnode, TargetFid.unique);
2386
2387         code = cm_GetSCache(&TargetFid, &newDscp->fid, &scp, userp, &req);
2388         if (code) {
2389             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target failed code 0x%x", code);
2390             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2391             (*ResultCB)->ResultStatus = status;
2392             cm_ReleaseSCache(oldDscp);
2393             cm_ReleaseSCache(newDscp);
2394             return;
2395         }
2396
2397         /* Make sure the source vnode is current */
2398         lock_ObtainWrite(&scp->rw);
2399         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2400                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2401         if (code) {
2402             osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp scp 0x%p failed code 0x%x", scp, code);
2403             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2404             (*ResultCB)->ResultStatus = status;
2405             lock_ReleaseWrite(&scp->rw);
2406             cm_ReleaseSCache(oldDscp);
2407             cm_ReleaseSCache(newDscp);
2408             cm_ReleaseSCache(scp);
2409             return;
2410         }
2411
2412         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2413         lock_ReleaseWrite(&scp->rw);
2414
2415         if (cm_shortNames) {
2416             dfid.vnode = htonl(scp->fid.vnode);
2417             dfid.unique = htonl(scp->fid.unique);
2418
2419             if (!cm_Is8Dot3(TargetFileName))
2420                 cm_Gen8Dot3NameIntW(TargetFileName, &dfid, shortName, NULL);
2421             else
2422                 shortName[0] = '\0';
2423         }
2424
2425         RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
2426                                  newDscp, scp, userp, &req, TargetFileName, shortName,
2427                                  RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
2428                                  0, NULL, &dwRemaining);
2429         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
2430         cm_ReleaseSCache(scp);
2431
2432         osi_Log0(afsd_logp, "RDR_RenameFileEntry SUCCESS");
2433     } else {
2434         osi_Log3(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p failed code 0x%x",
2435                  oldDscp, newDscp, code);
2436         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2437         (*ResultCB)->ResultStatus = status;
2438         (*ResultCB)->ResultBufferLength = 0;
2439     }
2440
2441     cm_ReleaseSCache(oldDscp);
2442     cm_ReleaseSCache(newDscp);
2443     return;
2444 }
2445
2446 void
2447 RDR_FlushFileEntry( IN cm_user_t *userp,
2448                     IN AFSFileID FileId,
2449                     IN BOOL bWow64,
2450                     IN DWORD ResultBufferLength,
2451                     IN OUT AFSCommResult **ResultCB)
2452 {
2453     cm_scache_t *scp = NULL;
2454     cm_fid_t    Fid;
2455     afs_uint32  code;
2456     cm_req_t    req;
2457     DWORD       status;
2458 #ifdef ODS_DEBUG
2459     char        dbgstr[1024];
2460 #endif
2461
2462     RDR_InitReq(&req, bWow64);
2463
2464     osi_Log4(afsd_logp, "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x",
2465               FileId.Cell, FileId.Volume,
2466               FileId.Vnode, FileId.Unique);
2467 #ifdef ODS_DEBUG
2468     snprintf( dbgstr, 1024,
2469               "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x\n",
2470               FileId.Cell, FileId.Volume,
2471               FileId.Vnode, FileId.Unique);
2472     OutputDebugStringA( dbgstr);
2473 #endif
2474
2475     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
2476     if (!(*ResultCB)) {
2477         osi_Log0(afsd_logp, "RDR_FlushFileEntry out of memory");
2478         return;
2479     }
2480
2481     memset( *ResultCB,
2482             '\0',
2483             sizeof( AFSCommResult));
2484
2485     /* Process the release */
2486     Fid.cell = FileId.Cell;
2487     Fid.volume = FileId.Volume;
2488     Fid.vnode = FileId.Vnode;
2489     Fid.unique = FileId.Unique;
2490     Fid.hash = FileId.Hash;
2491
2492     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
2493     if (code) {
2494         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2495         (*ResultCB)->ResultStatus = status;
2496         osi_Log2(afsd_logp, "RDR_FlushFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
2497                   code, status);
2498         return;
2499     }
2500
2501     lock_ObtainWrite(&scp->rw);
2502     if (scp->flags & CM_SCACHEFLAG_DELETED) {
2503         lock_ReleaseWrite(&scp->rw);
2504         (*ResultCB)->ResultStatus = STATUS_INVALID_HANDLE;
2505         return;
2506     }
2507
2508     code = cm_SyncOp(scp, NULL, userp, &req, 0,
2509                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2510     if (code) {
2511         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2512         (*ResultCB)->ResultStatus = status;
2513         lock_ReleaseWrite(&scp->rw);
2514         cm_ReleaseSCache(scp);
2515         osi_Log3(afsd_logp, "RDR_FlushFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2516                  scp, code, status);
2517         return;
2518     }
2519
2520     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2521     lock_ReleaseWrite(&scp->rw);
2522
2523     code = cm_FSync(scp, userp, &req, FALSE);
2524     cm_ReleaseSCache(scp);
2525
2526     if (code) {
2527         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2528         (*ResultCB)->ResultStatus = status;
2529         osi_Log2(afsd_logp, "RDR_FlushFileEntry FAILURE code=0x%x status=0x%x",
2530                   code, status);
2531     } else {
2532         (*ResultCB)->ResultStatus = 0;
2533         osi_Log0(afsd_logp, "RDR_FlushFileEntry SUCCESS");
2534     }
2535     (*ResultCB)->ResultBufferLength = 0;
2536
2537     return;
2538 }
2539
2540 afs_uint32
2541 RDR_CheckAccess( IN cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
2542                  ULONG access,
2543                  ULONG *granted)
2544 {
2545     ULONG afs_acc, afs_gr;
2546     BOOLEAN file, dir;
2547     afs_uint32 code = 0;
2548
2549     file = (scp->fileType == CM_SCACHETYPE_FILE);
2550     dir = !file;
2551
2552     /* access definitions from prs_fs.h */
2553     afs_acc = 0;
2554     if (access & FILE_READ_DATA)
2555         afs_acc |= PRSFS_READ;
2556     if (access & FILE_READ_EA || access & FILE_READ_ATTRIBUTES)
2557         afs_acc |= PRSFS_READ;
2558     if (file && ((access & FILE_WRITE_DATA) || (access & FILE_APPEND_DATA)))
2559         afs_acc |= PRSFS_WRITE;
2560     if (access & FILE_WRITE_EA || access & FILE_WRITE_ATTRIBUTES)
2561         afs_acc |= PRSFS_WRITE;
2562     if (dir && ((access & FILE_ADD_FILE) || (access & FILE_ADD_SUBDIRECTORY)))
2563         afs_acc |= PRSFS_INSERT;
2564     if (dir && (access & FILE_LIST_DIRECTORY))
2565         afs_acc |= PRSFS_LOOKUP;
2566     if (file && (access & FILE_EXECUTE))
2567         afs_acc |= PRSFS_WRITE;
2568     if (dir && (access & FILE_TRAVERSE))
2569         afs_acc |= PRSFS_READ;
2570     if (dir && (access & FILE_DELETE_CHILD))
2571         afs_acc |= PRSFS_DELETE;
2572     if ((access & DELETE))
2573         afs_acc |= PRSFS_DELETE;
2574
2575     /* check ACL with server */
2576     lock_ObtainWrite(&scp->rw);
2577     while (1)
2578     {
2579         if (cm_HaveAccessRights(scp, userp, reqp, afs_acc, &afs_gr))
2580         {
2581             break;
2582         }
2583         else
2584         {
2585             /* we don't know the required access rights */
2586             code = cm_GetAccessRights(scp, userp, reqp);
2587             if (code)
2588                 break;
2589             continue;
2590         }
2591     }
2592     lock_ReleaseWrite(&(scp->rw));
2593
2594     if (code == 0) {
2595         *granted = 0;
2596         if (afs_gr & PRSFS_READ)
2597             *granted |= FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | FILE_EXECUTE;
2598         if (afs_gr & PRSFS_WRITE)
2599             *granted |= FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | FILE_EXECUTE;
2600         if (afs_gr & PRSFS_INSERT)
2601             *granted |= (dir ? FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY : 0) | (file ? FILE_ADD_SUBDIRECTORY : 0);
2602         if (afs_gr & PRSFS_LOOKUP)
2603             *granted |= (dir ? FILE_LIST_DIRECTORY : 0);
2604         if (afs_gr & PRSFS_DELETE)
2605             *granted |= FILE_DELETE_CHILD | DELETE;
2606         if (afs_gr & PRSFS_LOCK)
2607             *granted |= 0;
2608         if (afs_gr & PRSFS_ADMINISTER)
2609             *granted |= 0;
2610
2611         *granted |= SYNCHRONIZE | READ_CONTROL;
2612
2613         /* don't give more access than what was requested */
2614         *granted &= access;
2615         osi_Log3(afsd_logp, "RDR_CheckAccess SUCCESS scp=0x%p requested=0x%x granted=0x%x", scp, access, *granted);
2616     } else
2617         osi_Log2(afsd_logp, "RDR_CheckAccess FAILURE scp=0x%p code=0x%x",
2618                  scp, code);
2619
2620     return code;
2621 }
2622
2623 void
2624 RDR_OpenFileEntry( IN cm_user_t *userp,
2625                    IN AFSFileID FileId,
2626                    IN AFSFileOpenCB *OpenCB,
2627                    IN BOOL bWow64,
2628                    IN BOOL bHoldFid,
2629                    IN DWORD ResultBufferLength,
2630                    IN OUT AFSCommResult **ResultCB)
2631 {
2632     AFSFileOpenResultCB *pResultCB = NULL;
2633     cm_scache_t *scp = NULL;
2634     cm_user_t   *sysUserp = NULL;
2635     cm_fid_t    Fid;
2636     cm_lock_data_t      *ldp = NULL;
2637     afs_uint32  code;
2638     cm_req_t    req;
2639     DWORD       status;
2640
2641     RDR_InitReq(&req, bWow64);
2642
2643     osi_Log4(afsd_logp, "RDR_OpenFileEntry File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2644               FileId.Cell, FileId.Volume,
2645               FileId.Vnode, FileId.Unique);
2646
2647     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
2648     if (!(*ResultCB)) {
2649         osi_Log0(afsd_logp, "RDR_OpenFileEntry out of memory");
2650         return;
2651     }
2652
2653     memset( *ResultCB,
2654             '\0',
2655             sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
2656
2657     pResultCB = (AFSFileOpenResultCB *)(*ResultCB)->ResultData;
2658
2659     /* Process the release */
2660     Fid.cell = FileId.Cell;
2661     Fid.volume = FileId.Volume;
2662     Fid.vnode = FileId.Vnode;
2663     Fid.unique = FileId.Unique;
2664     Fid.hash = FileId.Hash;
2665
2666     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
2667     if (code) {
2668         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2669         (*ResultCB)->ResultStatus = status;
2670         osi_Log2(afsd_logp, "RDR_OpenFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
2671                   code, status);
2672         return;
2673     }
2674
2675     lock_ObtainWrite(&scp->rw);
2676     code = cm_SyncOp(scp, NULL, userp, &req, 0,
2677                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2678     if (code) {
2679         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2680         (*ResultCB)->ResultStatus = status;
2681         lock_ReleaseWrite(&scp->rw);
2682         cm_ReleaseSCache(scp);
2683         osi_Log3(afsd_logp, "RDR_OpenFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2684                  scp, code, status);
2685         return;
2686     }
2687
2688     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2689     lock_ReleaseWrite(&scp->rw);
2690
2691     sysUserp = RDR_GetLocalSystemUser();
2692
2693     /*
2694      * Skip the open check if the request is coming from the local system account.
2695      * The local system has no tokens and therefore any requests sent to a file
2696      * server will fail.  Unfortunately, there are special system processes that
2697      * perform actions on files and directories in preparation for memory mapping
2698      * executables.  If the open check fails, the real request from the user process
2699      * will never be issued.
2700      *
2701      * Permitting the file system to allow subsequent operations to proceed does
2702      * not compromise security.  All requests to obtain file data or directory
2703      * enumerations will subsequently fail if they are not submitted under the
2704      * context of a process for that have access to the necessary credentials.
2705      */
2706
2707     if ( userp == sysUserp)
2708     {
2709         osi_Log1(afsd_logp, "RDR_OpenFileEntry LOCAL_SYSTEM access check skipped scp=0x%p",
2710                  scp);
2711         pResultCB->GrantedAccess = OpenCB->DesiredAccess;
2712         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
2713         code = 0;
2714     }
2715     else
2716     {
2717         int count = 0;
2718
2719         do {
2720             if (count++ > 0) {
2721                 Sleep(350);
2722                 osi_Log3(afsd_logp,
2723                          "RDR_OpenFileEntry repeating open check scp=0x%p userp=0x%p code=0x%x",
2724                          scp, userp, code);
2725             }
2726             code = cm_CheckNTOpen(scp, OpenCB->DesiredAccess, OpenCB->ShareAccess,
2727                                   OPEN_ALWAYS,
2728                                   OpenCB->ProcessId, OpenCB->Identifier,
2729                                   userp, &req, &ldp);
2730             if (code == 0)
2731                 code = RDR_CheckAccess(scp, userp, &req, OpenCB->DesiredAccess, &pResultCB->GrantedAccess);
2732             cm_CheckNTOpenDone(scp, userp, &req, &ldp);
2733         } while (count < 100 && (code == CM_ERROR_RETRY || code == CM_ERROR_WOULDBLOCK));
2734     }
2735
2736     /*
2737      * If we are restricting sharing, we should do so with a suitable
2738      * share lock.
2739      */
2740     if (code == 0 && scp->fileType == CM_SCACHETYPE_FILE && !(OpenCB->ShareAccess & FILE_SHARE_WRITE)) {
2741         cm_key_t key;
2742         LARGE_INTEGER LOffset, LLength;
2743         int sLockType;
2744
2745         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
2746         LOffset.LowPart = SMB_FID_QLOCK_LOW;
2747         LLength.HighPart = 0;
2748         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
2749
2750         /*
2751          * If we are not opening the file for writing, then we don't
2752          * try to get an exclusive lock.  No one else should be able to
2753          * get an exclusive lock on the file anyway, although someone
2754          * else can get a shared lock.
2755          */
2756         if ((OpenCB->ShareAccess & FILE_SHARE_READ) || !(OpenCB->DesiredAccess & AFS_ACCESS_WRITE))
2757         {
2758             sLockType = LOCKING_ANDX_SHARED_LOCK;
2759         } else {
2760             sLockType = 0;
2761         }
2762
2763         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, OpenCB->Identifier);
2764
2765         lock_ObtainWrite(&scp->rw);
2766         code = cm_Lock(scp, sLockType, LOffset, LLength, key, 0, userp, &req, NULL);
2767         lock_ReleaseWrite(&scp->rw);
2768
2769         if (code) {
2770             code = CM_ERROR_SHARING_VIOLATION;
2771             pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
2772         } else {
2773             if (sLockType == LOCKING_ANDX_SHARED_LOCK)
2774                 pResultCB->FileAccess = AFS_FILE_ACCESS_SHARED;
2775             else
2776                 pResultCB->FileAccess = AFS_FILE_ACCESS_EXCLUSIVE;
2777         }
2778     } else {
2779         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
2780     }
2781
2782     cm_ReleaseUser(sysUserp);
2783     if (code == 0 && bHoldFid)
2784         RDR_FlagScpInUse( scp, FALSE );
2785     cm_ReleaseSCache(scp);
2786
2787     if (code) {
2788         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2789         (*ResultCB)->ResultStatus = status;
2790         osi_Log2(afsd_logp, "RDR_OpenFileEntry FAILURE code=0x%x status=0x%x",
2791                   code, status);
2792     } else {
2793         (*ResultCB)->ResultStatus = 0;
2794         (*ResultCB)->ResultBufferLength = sizeof( AFSFileOpenResultCB);
2795         osi_Log0(afsd_logp, "RDR_OpenFileEntry SUCCESS");
2796     }
2797     return;
2798 }
2799
2800 void
2801 RDR_ReleaseFileAccess( IN cm_user_t *userp,
2802                        IN AFSFileID FileId,
2803                        IN AFSFileAccessReleaseCB *ReleaseFileCB,
2804                        IN BOOL bWow64,
2805                        IN DWORD ResultBufferLength,
2806                        IN OUT AFSCommResult **ResultCB)
2807 {
2808     cm_key_t key;
2809     unsigned int sLockType;
2810     LARGE_INTEGER LOffset, LLength;
2811     cm_scache_t *scp = NULL;
2812     cm_fid_t    Fid;
2813     afs_uint32  code;
2814     cm_req_t    req;
2815     DWORD       status;
2816
2817     RDR_InitReq(&req, bWow64);
2818
2819     osi_Log4(afsd_logp, "RDR_ReleaseFileAccess File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2820               FileId.Cell, FileId.Volume,
2821               FileId.Vnode, FileId.Unique);
2822
2823     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
2824     if (!(*ResultCB)) {
2825         osi_Log0(afsd_logp, "RDR_ReleaseFileAccess out of memory");
2826         return;
2827     }
2828
2829     memset( *ResultCB, '\0', sizeof( AFSCommResult));
2830
2831     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_NOLOCK)
2832         return;
2833
2834     /* Process the release */
2835     Fid.cell = FileId.Cell;
2836     Fid.volume = FileId.Volume;
2837     Fid.vnode = FileId.Vnode;
2838     Fid.unique = FileId.Unique;
2839     Fid.hash = FileId.Hash;
2840
2841     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
2842     if (code) {
2843         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2844         (*ResultCB)->ResultStatus = status;
2845         osi_Log2(afsd_logp, "RDR_ReleaseFileAccess cm_GetSCache FID failure code=0x%x status=0x%x",
2846                   code, status);
2847         return;
2848     }
2849
2850     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_SHARED)
2851         sLockType = LOCKING_ANDX_SHARED_LOCK;
2852     else
2853         sLockType = 0;
2854
2855     key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, ReleaseFileCB->Identifier);
2856
2857     LOffset.HighPart = SMB_FID_QLOCK_HIGH;
2858     LOffset.LowPart = SMB_FID_QLOCK_LOW;
2859     LLength.HighPart = 0;
2860     LLength.LowPart = SMB_FID_QLOCK_LENGTH;
2861
2862     lock_ObtainWrite(&scp->rw);
2863
2864     code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
2865     if (code == 0)
2866     {
2867         code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
2868
2869         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
2870
2871         if (code == CM_ERROR_RANGE_NOT_LOCKED)
2872         {
2873             osi_Log3(afsd_logp, "RDR_ReleaseFileAccess Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
2874                      ReleaseFileCB->FileAccess, ReleaseFileCB->ProcessId, ReleaseFileCB->Identifier);
2875         }
2876     }
2877
2878     lock_ReleaseWrite(&scp->rw);
2879
2880     osi_Log0(afsd_logp, "RDR_ReleaseFileAccessEntry SUCCESS");
2881 }
2882
2883 static const char *
2884 HexCheckSum(unsigned char * buf, int buflen, unsigned char * md5cksum)
2885 {
2886     int i, k;
2887     static char tr[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
2888
2889     if (buflen < 33)
2890         return "buffer length too small to HexCheckSum";
2891
2892     for (i=0;i<16;i++) {
2893         k = md5cksum[i];
2894
2895         buf[i*2] = tr[k / 16];
2896         buf[i*2+1] = tr[k % 16];
2897     }
2898     buf[32] = '\0';
2899
2900     return buf;
2901 }
2902
2903 /*
2904  * Extent requests from the file system are triggered when a file
2905  * page is not resident in the Windows cache.  The file system is
2906  * responsible for loading the page but cannot block the request
2907  * while doing so.  The AFS Redirector forwards the requests to
2908  * the AFS cache manager while indicating to Windows that the page
2909  * is not yet available.  A polling operation will then ensue with
2910  * the AFS Redirector issuing a RDR_RequestFileExtentsXXX call for
2911  * each poll attempt.  As each request is received and processed
2912  * by a separate worker thread in the service, this can lead to
2913  * contention by multiple threads attempting to claim the same
2914  * cm_buf_t objects.  Therefore, it is important that
2915  *
2916  *  (a) the service avoid processing more than one overlapping
2917  *      extent request at a time
2918  *  (b) background daemon processing be used to avoid blocking
2919  *      of ioctl threads
2920  *
2921  * Beginning with the 20091122 build of the redirector, the redirector
2922  * will not issue an additional RDR_RequestFileExtentsXXX call for
2923  * each poll request.  Instead, afsd_service is required to track
2924  * the requests and return them to the redirector or fail the
2925  * portions of the request that cannot be satisfied.
2926  *
2927  * The request processing returns any extents that can be returned
2928  * immediately to the redirector.  The rest of the requested range(s)
2929  * are queued as background operations using RDR_BkgFetch().
2930  */
2931
2932 /* do the background fetch. */
2933 afs_int32
2934 RDR_BkgFetch(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
2935              cm_user_t *userp, cm_req_t *reqp)
2936 {
2937     osi_hyper_t length;
2938     osi_hyper_t base;
2939     osi_hyper_t offset;
2940     osi_hyper_t end;
2941     osi_hyper_t fetched;
2942     osi_hyper_t tblocksize;
2943     afs_int32 code;
2944     int rwheld = 0;
2945     cm_buf_t *bufp = NULL;
2946     DWORD dwResultBufferLength;
2947     AFSSetFileExtentsCB *pResultCB;
2948     DWORD status;
2949     afs_uint32 count=0;
2950     AFSFileID FileId;
2951     int reportErrorToRedir = 0;
2952     int force_retry = 0;
2953
2954     FileId.Cell = scp->fid.cell;
2955     FileId.Volume = scp->fid.volume;
2956     FileId.Vnode = scp->fid.vnode;
2957     FileId.Unique = scp->fid.unique;
2958     FileId.Hash = scp->fid.hash;
2959
2960     fetched.LowPart = 0;
2961     fetched.HighPart = 0;
2962     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
2963     base.LowPart = p1;
2964     base.HighPart = p2;
2965     length.LowPart = p3;
2966     length.HighPart = p4;
2967
2968     end = LargeIntegerAdd(base, length);
2969
2970     osi_Log5(afsd_logp, "Starting BKG Fetch scp 0x%p offset 0x%x:%x length 0x%x:%x",
2971              scp, p2, p1, p4, p3);
2972
2973     /*
2974      * Make sure we have a callback.
2975      * This is necessary so that we can return access denied
2976      * if a callback cannot be granted.
2977      */
2978     lock_ObtainWrite(&scp->rw);
2979     code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_READ,
2980                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2981     if (code) {
2982         lock_ReleaseWrite(&scp->rw);
2983         osi_Log2(afsd_logp, "RDR_BkgFetch cm_SyncOp failure scp=0x%p code=0x%x",
2984                  scp, code);
2985         smb_MapNTError(cm_MapRPCError(code, reqp), &status, TRUE);
2986         RDR_SetFileStatus( &scp->fid, &userp->authgroup, status);
2987         return code;
2988     }
2989     lock_ReleaseWrite(&scp->rw);
2990
2991     dwResultBufferLength = (DWORD)(sizeof( AFSSetFileExtentsCB) + sizeof( AFSFileExtentCB) * (length.QuadPart / cm_data.blockSize + 1));
2992     pResultCB = (AFSSetFileExtentsCB *)malloc( dwResultBufferLength );
2993     if (!pResultCB)
2994         return CM_ERROR_RETRY;
2995
2996     memset( pResultCB, '\0', dwResultBufferLength );
2997     pResultCB->FileId = FileId;
2998
2999     for ( code = 0, offset = base;
3000           code == 0 && LargeIntegerLessThan(offset, end);
3001           offset = LargeIntegerAdd(offset, tblocksize) )
3002     {
3003         int bBufRelease = TRUE;
3004
3005         if (rwheld) {
3006             lock_ReleaseWrite(&scp->rw);
3007             rwheld = 0;
3008         }
3009
3010         code = buf_Get(scp, &offset, reqp, &bufp);
3011         if (code) {
3012             /*
3013              * any error from buf_Get() is non-fatal.
3014              * we need to re-queue this extent fetch.
3015              */
3016             force_retry = 1;
3017             break;
3018         }
3019
3020         if (!rwheld) {
3021             lock_ObtainWrite(&scp->rw);
3022             rwheld = 1;
3023         }
3024
3025         code = cm_GetBuffer(scp, bufp, NULL, userp, reqp);
3026         if (code == 0) {
3027             if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3028 #ifdef VALIDATE_CHECK_SUM
3029 #ifdef ODS_DEBUG
3030                 char md5dbg[33];
3031                 char dbgstr[1024];
3032 #endif
3033 #endif
3034                 if (bufp->flags & CM_BUF_DIRTY)
3035                     cm_BufWrite(scp, &bufp->offset, cm_data.buf_blockSize, CM_BUF_WRITE_SCP_LOCKED, userp, reqp);
3036
3037                 lock_ObtainWrite(&buf_globalLock);
3038                 if (!(bufp->flags & CM_BUF_DIRTY) &&
3039                     bufp->cmFlags == 0 &&
3040                     !(bufp->qFlags & CM_BUF_QREDIR)) {
3041                     buf_InsertToRedirQueue(scp, bufp);
3042                     lock_ReleaseWrite(&buf_globalLock);
3043
3044 #ifdef VALIDATE_CHECK_SUM
3045                     buf_ComputeCheckSum(bufp);
3046 #endif
3047                     pResultCB->FileExtents[count].Flags = 0;
3048                     pResultCB->FileExtents[count].FileOffset.QuadPart = bufp->offset.QuadPart;
3049                     pResultCB->FileExtents[count].CacheOffset.QuadPart = bufp->datap - RDR_extentBaseAddress;
3050                     pResultCB->FileExtents[count].Length = cm_data.blockSize;
3051                     count++;
3052                     fetched = LargeIntegerAdd(fetched, tblocksize);
3053                     bBufRelease = FALSE;
3054
3055 #ifdef VALIDATE_CHECK_SUM
3056 #ifdef ODS_DEBUG
3057                     HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3058                     snprintf( dbgstr, 1024,
3059                               "RDR_BkgFetch md5 %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3060                               md5dbg,
3061                               scp->fid.volume, scp->fid.vnode, scp->fid.unique,
3062                               pResultCB->FileExtents[count].FileOffset.HighPart,
3063                               pResultCB->FileExtents[count].FileOffset.LowPart,
3064                               pResultCB->FileExtents[count].CacheOffset.HighPart,
3065                               pResultCB->FileExtents[count].CacheOffset.LowPart);
3066                     OutputDebugStringA( dbgstr);
3067 #endif
3068 #endif
3069                     osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3070                               bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3071                 } else {
3072                     lock_ReleaseWrite(&buf_globalLock);
3073                     if ((bufp->cmFlags != 0) || (bufp->flags & CM_BUF_DIRTY)) {
3074                         /* An I/O operation is already in progress */
3075                         force_retry = 1;
3076                         osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS Not delivering to Redirector Dirty or Busy bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3077                                   bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3078                     } else {
3079                         osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS Already held by Redirector bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3080                                   bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3081                     }
3082                 }
3083             } else {
3084                 osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS Already held by Redirector bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3085                           bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3086             }
3087         } else {
3088             /*
3089              * depending on what the error from cm_GetBuffer is
3090              * it may or may not be fatal.  Only return fatal errors.
3091              * Re-queue a request for others.
3092              */
3093             osi_Log5(afsd_logp, "RDR_BkgFetch Extent2FS FAILURE bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x code 0x%x",
3094                       bufp, offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize, code);
3095             switch (code) {
3096             case CM_ERROR_NOACCESS:
3097             case CM_ERROR_NOSUCHFILE:
3098             case CM_ERROR_NOSUCHPATH:
3099             case CM_ERROR_NOSUCHVOLUME:
3100             case CM_ERROR_NOSUCHCELL:
3101             case CM_ERROR_INVAL:
3102             case CM_ERROR_BADFD:
3103             case CM_ERROR_CLOCKSKEW:
3104             case RXKADNOAUTH:
3105             case CM_ERROR_QUOTA:
3106             case CM_ERROR_LOCK_CONFLICT:
3107                 /*
3108                  * these are fatal errors.  deliver what we can
3109                  * and halt.
3110                  */
3111                 reportErrorToRedir = 1;
3112                 break;
3113             default:
3114                 /*
3115                  * non-fatal errors.  re-queue the exent
3116                  */
3117                 code = CM_ERROR_RETRY;
3118                 force_retry = 1;
3119             }
3120         }
3121
3122         if (bBufRelease)
3123             buf_Release(bufp);
3124     }
3125
3126     if (!rwheld) {
3127         lock_ObtainWrite(&scp->rw);
3128         rwheld = 1;
3129     }
3130
3131     /* wakeup anyone who is waiting */
3132     if (scp->flags & CM_SCACHEFLAG_WAITING) {
3133         osi_Log1(afsd_logp, "RDR Bkg Fetch Waking scp 0x%p", scp);
3134         osi_Wakeup((LONG_PTR) &scp->flags);
3135     }
3136     lock_ReleaseWrite(&scp->rw);
3137
3138     if (count > 0) {
3139         pResultCB->ExtentCount = count;
3140         RDR_SetFileExtents( pResultCB, dwResultBufferLength);
3141     }
3142     free(pResultCB);
3143
3144     if (reportErrorToRedir) {
3145         smb_MapNTError(cm_MapRPCError(code, reqp), &status, TRUE);
3146         RDR_SetFileStatus( &scp->fid, &userp->authgroup, status);
3147     }
3148
3149     osi_Log4(afsd_logp, "Ending BKG Fetch scp 0x%p code 0x%x fetched 0x%x:%x",
3150              scp, code, fetched.HighPart, fetched.LowPart);
3151
3152     return force_retry ? CM_ERROR_RETRY : code;
3153 }
3154
3155
3156 BOOL
3157 RDR_RequestFileExtentsAsync( IN cm_user_t *userp,
3158                              IN AFSFileID FileId,
3159                              IN AFSRequestExtentsCB *RequestExtentsCB,
3160                              IN BOOL bWow64,
3161                              IN OUT DWORD * ResultBufferLength,
3162                              IN OUT AFSSetFileExtentsCB **ResultCB)
3163 {
3164     AFSSetFileExtentsCB *pResultCB = NULL;
3165     DWORD Length;
3166     DWORD count;
3167     DWORD status;
3168     cm_scache_t *scp = NULL;
3169     cm_fid_t    Fid;
3170     cm_buf_t    *bufp;
3171     afs_uint32  code = 0;
3172     osi_hyper_t thyper;
3173     LARGE_INTEGER ByteOffset, BeginOffset, EndOffset, QueueOffset;
3174     afs_uint32  QueueLength;
3175     cm_req_t    req;
3176     BOOLEAN     bBufRelease = TRUE;
3177
3178     RDR_InitReq(&req, bWow64);
3179     req.flags |= CM_REQ_NORETRY;
3180
3181     osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3182               FileId.Cell, FileId.Volume,
3183               FileId.Vnode, FileId.Unique);
3184     osi_Log4(afsd_logp, "... Flags 0x%x ByteOffset 0x%x:%x Length 0x%x",
3185              RequestExtentsCB->Flags,
3186              RequestExtentsCB->ByteOffset.HighPart, RequestExtentsCB->ByteOffset.LowPart,
3187              RequestExtentsCB->Length);
3188     Length = sizeof( AFSSetFileExtentsCB) + sizeof( AFSFileExtentCB) * (RequestExtentsCB->Length / cm_data.blockSize + 1);
3189
3190     pResultCB = *ResultCB = (AFSSetFileExtentsCB *)malloc( Length );
3191     if (*ResultCB == NULL) {
3192         *ResultBufferLength = 0;
3193         return FALSE;
3194     }
3195     *ResultBufferLength = Length;
3196
3197     memset( pResultCB, '\0', Length );
3198     pResultCB->FileId = FileId;
3199
3200     Fid.cell = FileId.Cell;
3201     Fid.volume = FileId.Volume;
3202     Fid.vnode = FileId.Vnode;
3203     Fid.unique = FileId.Unique;
3204     Fid.hash = FileId.Hash;
3205
3206     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3207     if (code) {
3208         osi_Log1(afsd_logp, "RDR_RequestFileExtentsAsync cm_GetSCache FID failure code=0x%x",
3209                   code);
3210         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3211         return FALSE;
3212     }
3213
3214     /*
3215      * Make sure we have a callback.
3216      * This is necessary so that we can return access denied
3217      * if a callback cannot be granted.
3218      */
3219     lock_ObtainWrite(&scp->rw);
3220     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_READ,
3221                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3222     lock_ReleaseWrite(&scp->rw);
3223     if (code) {
3224         cm_ReleaseSCache(scp);
3225         osi_Log2(afsd_logp, "RDR_RequestFileExtentsAsync cm_SyncOp failure scp=0x%p code=0x%x",
3226                  scp, code);
3227         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3228         RDR_SetFileStatus( &scp->fid, &userp->authgroup, status);
3229         return FALSE;
3230     }
3231
3232     /* Allocate the extents from the buffer package */
3233     for ( count = 0,
3234           ByteOffset = BeginOffset = RequestExtentsCB->ByteOffset,
3235           EndOffset.QuadPart = ByteOffset.QuadPart + RequestExtentsCB->Length;
3236           code == 0 && ByteOffset.QuadPart < EndOffset.QuadPart;
3237           ByteOffset.QuadPart += cm_data.blockSize)
3238     {
3239         BOOL bHaveBuffer = FALSE;
3240
3241         QueueLength = 0;
3242         thyper.QuadPart = ByteOffset.QuadPart;
3243
3244         code = buf_Get(scp, &thyper, &req, &bufp);
3245         if (code == 0) {
3246             lock_ObtainMutex(&bufp->mx);
3247             bBufRelease = TRUE;
3248
3249             if (bufp->qFlags & CM_BUF_QREDIR) {
3250                 bHaveBuffer = TRUE;
3251             } else if (bufp->flags & CM_BUF_DIRTY) {
3252                 bHaveBuffer = FALSE;
3253 #if 0
3254                 code = buf_CleanAsyncLocked(scp, bufp, &req, 0, NULL);
3255                 switch (code) {
3256                 case 0:
3257                     bHaveBuffer = TRUE;
3258                     break;
3259                 case CM_ERROR_RETRY:
3260                     /* Couldn't flush it, obtain it asynchronously so we don't block the thread. */
3261                     bHaveBuffer = FALSE;
3262                     code = 0;
3263                     break;
3264                 default:
3265                     smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3266                     RDR_SetFileStatus(&FileId, &userp->authgroup, status);
3267                     bHaveBuffer = FALSE;
3268                     code = 0;
3269                 }
3270 #endif
3271             } else {
3272                 osi_hyper_t minLength;  /* effective end of file */
3273
3274                 lock_ObtainRead(&scp->rw);
3275                 bHaveBuffer = cm_HaveBuffer(scp, bufp, TRUE);
3276
3277                 if (LargeIntegerGreaterThan(scp->length, scp->serverLength))
3278                     minLength = scp->serverLength;
3279                 else
3280                     minLength = scp->length;
3281
3282                 if (LargeIntegerGreaterThanOrEqualTo(bufp->offset, minLength)) {
3283                     if (!bHaveBuffer) {
3284                         memset(bufp->datap, 0, cm_data.buf_blockSize);
3285                         bufp->dataVersion = scp->dataVersion;
3286                         bHaveBuffer = TRUE;
3287                     }
3288                     else if (bufp->dataVersion == CM_BUF_VERSION_BAD) {
3289                         bufp->dataVersion = scp->dataVersion;
3290                     }
3291                 }
3292                 else if ((RequestExtentsCB->Flags & AFS_EXTENT_FLAG_CLEAN) &&
3293                          ByteOffset.QuadPart <= bufp->offset.QuadPart &&
3294                          EndOffset.QuadPart >= bufp->offset.QuadPart + cm_data.blockSize)
3295                 {
3296                     memset(bufp->datap, 0, cm_data.blockSize);
3297                     bufp->dataVersion = scp->dataVersion;
3298                     buf_SetDirty(bufp, &req, 0, cm_data.blockSize, userp);
3299                     bHaveBuffer = TRUE;
3300                 }
3301                 lock_ReleaseRead(&scp->rw);
3302             }
3303
3304             /*
3305              * if this buffer is already up to date, skip it.
3306              */
3307             if (bHaveBuffer) {
3308                 if (ByteOffset.QuadPart == BeginOffset.QuadPart) {
3309                     BeginOffset.QuadPart += cm_data.blockSize;
3310                 } else {
3311                     QueueLength = (afs_uint32)(ByteOffset.QuadPart - BeginOffset.QuadPart);
3312                     QueueOffset = BeginOffset;
3313                     BeginOffset = ByteOffset;
3314                 }
3315
3316                 if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3317 #ifdef VALIDATE_CHECK_SUM
3318 #ifdef ODS_DEBUG
3319                     char md5dbg[33];
3320                     char dbgstr[1024];
3321 #endif
3322 #endif
3323                     lock_ObtainWrite(&buf_globalLock);
3324                     if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3325                         buf_InsertToRedirQueue(scp, bufp);
3326                         lock_ReleaseWrite(&buf_globalLock);
3327
3328 #ifdef VALIDATE_CHECK_SUM
3329                         buf_ComputeCheckSum(bufp);
3330 #endif
3331                         /* we already have the buffer, return it now */
3332                         pResultCB->FileExtents[count].Flags = 0;
3333                         pResultCB->FileExtents[count].FileOffset = ByteOffset;
3334                         pResultCB->FileExtents[count].CacheOffset.QuadPart = bufp->datap - RDR_extentBaseAddress;
3335                         pResultCB->FileExtents[count].Length = cm_data.blockSize;
3336                         count++;
3337
3338                         bBufRelease = FALSE;
3339
3340 #ifdef VALIDATE_CHECK_SUM
3341 #ifdef ODS_DEBUG
3342                         HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3343                         snprintf( dbgstr, 1024,
3344                                   "RDR_RequestFileExtentsAsync md5 %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3345                                   md5dbg,
3346                                   scp->fid.volume, scp->fid.vnode, scp->fid.unique,
3347                                   pResultCB->FileExtents[count].FileOffset.HighPart,
3348                                   pResultCB->FileExtents[count].FileOffset.LowPart,
3349                                   pResultCB->FileExtents[count].CacheOffset.HighPart,
3350                                   pResultCB->FileExtents[count].CacheOffset.LowPart);
3351                         OutputDebugStringA( dbgstr);
3352 #endif
3353 #endif
3354                         osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync Extent2FS bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3355                                  bufp, ByteOffset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3356                     } else {
3357                         lock_ReleaseWrite(&buf_globalLock);
3358                     }
3359                 } else {
3360                     if (bBufRelease) {
3361                         /*
3362                          * The service is not handing off the extent to the redirector in this pass.
3363                          * However, we know the buffer is in recent use so move the buffer to the
3364                          * front of the queue
3365                          */
3366                         lock_ObtainWrite(&buf_globalLock);
3367                         buf_MoveToHeadOfRedirQueue(scp, bufp);
3368                         lock_ReleaseWrite(&buf_globalLock);
3369
3370                         osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync Extent2FS Already held by Redirector bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3371                                  bufp, ByteOffset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3372                     }
3373                 }
3374             }
3375             lock_ReleaseMutex(&bufp->mx);
3376             if (bBufRelease)
3377                 buf_Release(bufp);
3378
3379             if (QueueLength) {
3380                 cm_QueueBKGRequest(scp, RDR_BkgFetch, QueueOffset.LowPart, QueueOffset.HighPart,
3381                                    QueueLength, 0, userp, &req);
3382                 osi_Log3(afsd_logp, "RDR_RequestFileExtentsAsync Queued a Background Fetch offset 0x%x:%x length 0x%x",
3383                          QueueOffset.HighPart, QueueOffset.LowPart, QueueLength);
3384             }
3385         } else {
3386             /* No error from buf_Get() can be fatal */
3387             osi_Log3(afsd_logp, "RDR_RequestFileExtentsAsync buf_Get FAILURE offset 0x%x:%x code 0x%x",
3388                      BeginOffset.HighPart, BeginOffset.LowPart, code);
3389         }
3390     }
3391
3392     if (BeginOffset.QuadPart != EndOffset.QuadPart) {
3393         afs_uint32 length = (afs_uint32)(EndOffset.QuadPart - BeginOffset.QuadPart);
3394
3395         cm_QueueBKGRequest(scp, RDR_BkgFetch, BeginOffset.LowPart, BeginOffset.HighPart,
3396                            length, 0, userp, &req);
3397         osi_Log3(afsd_logp, "RDR_RequestFileExtentsAsync Queued a Background Fetch offset 0x%x:%x length 0x%x",
3398                   BeginOffset.HighPart, BeginOffset.LowPart, length);
3399     }
3400     cm_ReleaseSCache(scp);
3401
3402     (*ResultCB)->ExtentCount = count;
3403     osi_Log1(afsd_logp, "RDR_RequestFileExtentsAsync replying with 0x%x extent records", count);
3404     return FALSE;
3405 }
3406
3407 /*
3408  * When processing an extent release the extents must be accepted back by
3409  * the service even if there is an error condition returned to the redirector.
3410  * For example, there may no longer be a callback present or the file may
3411  * have been deleted on the file server.  Regardless, the extents must be
3412  * put back into the pool.
3413  */
3414 void
3415 RDR_ReleaseFileExtents( IN cm_user_t *userp,
3416                         IN AFSFileID FileId,
3417                         IN AFSReleaseExtentsCB *ReleaseExtentsCB,
3418                         IN BOOL bWow64,
3419                         IN DWORD ResultBufferLength,
3420                         IN OUT AFSCommResult **ResultCB)
3421 {
3422     DWORD count;
3423     cm_scache_t *scp = NULL;
3424     cm_fid_t    Fid;
3425     cm_buf_t    *bufp;
3426     afs_uint32  code;
3427     osi_hyper_t thyper;
3428     cm_req_t    req;
3429     int         dirty = 0;
3430     int         released = 0;
3431     int         deleted = 0;
3432     DWORD       status;
3433 #ifdef ODS_DEBUG
3434 #ifdef VALIDATE_CHECK_SUM
3435     char md5dbg[33], md5dbg2[33], md5dbg3[33];
3436 #endif
3437     char dbgstr[1024];
3438 #endif
3439
3440     RDR_InitReq(&req, bWow64);
3441
3442     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3443               FileId.Cell, FileId.Volume,
3444               FileId.Vnode, FileId.Unique);
3445
3446     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
3447     if (!(*ResultCB))
3448         return;
3449
3450     memset( *ResultCB,
3451             '\0',
3452             sizeof( AFSCommResult));
3453
3454     /* Process the release */
3455     Fid.cell = FileId.Cell;
3456     Fid.volume = FileId.Volume;
3457     Fid.vnode = FileId.Vnode;
3458     Fid.unique = FileId.Unique;
3459     Fid.hash = FileId.Hash;
3460
3461     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3462     if (code) {
3463         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3464         (*ResultCB)->ResultStatus = status;
3465         osi_Log2(afsd_logp, "RDR_ReleaseFileExtents cm_GetSCache FID failure code=0x%x status=0x%x",
3466                   code, status);
3467     }
3468
3469     deleted = scp && (scp->flags & CM_SCACHEFLAG_DELETED);
3470
3471     /*
3472      * We do not stop processing as a result of being unable to find the cm_scache object.
3473      * If this occurs something really bad has happened since the cm_scache object must have
3474      * been recycled while extents were held by the redirector.  However, we will be resilient
3475      * and carry on without it.
3476      *
3477      * If the file is known to be deleted, there is no point attempting to ask the
3478      * file server about it or update the attributes.
3479      */
3480     if (scp && ReleaseExtentsCB->AllocationSize.QuadPart != scp->length.QuadPart &&
3481         !deleted)
3482     {
3483         cm_attr_t setAttr;
3484
3485         memset(&setAttr, 0, sizeof(cm_attr_t));
3486         lock_ObtainWrite(&scp->rw);
3487         if (ReleaseExtentsCB->AllocationSize.QuadPart != scp->length.QuadPart) {
3488
3489             osi_Log4(afsd_logp, "RDR_ReleaseFileExtents new length fid vol 0x%x vno 0x%x length 0x%x:%x",
3490                       scp->fid.volume, scp->fid.vnode,
3491                       ReleaseExtentsCB->AllocationSize.HighPart,
3492                       ReleaseExtentsCB->AllocationSize.LowPart);
3493
3494             setAttr.mask |= CM_ATTRMASK_LENGTH;
3495             setAttr.length.LowPart = ReleaseExtentsCB->AllocationSize.LowPart;
3496             setAttr.length.HighPart = ReleaseExtentsCB->AllocationSize.HighPart;
3497         }
3498         lock_ReleaseWrite(&scp->rw);
3499         if (setAttr.mask)
3500             code = cm_SetAttr(scp, &setAttr, userp, &req);
3501     }
3502
3503     for ( count = 0; count < ReleaseExtentsCB->ExtentCount; count++) {
3504         AFSFileExtentCB * pExtent = &ReleaseExtentsCB->FileExtents[count];
3505
3506         thyper.QuadPart = pExtent->FileOffset.QuadPart;
3507
3508         bufp = buf_Find(&Fid, &thyper);
3509         if (bufp) {
3510             if (pExtent->Flags & AFS_EXTENT_FLAG_UNKNOWN) {
3511                 if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3512                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents extent vol 0x%x vno 0x%x foffset 0x%x:%x",
3513                               Fid.volume, Fid.vnode,
3514                               pExtent->FileOffset.HighPart,
3515                               pExtent->FileOffset.LowPart);
3516                     osi_Log2(afsd_logp, "... coffset 0x%x:%x UNKNOWN to redirector; previously released",
3517                               pExtent->CacheOffset.HighPart,
3518                               pExtent->CacheOffset.LowPart);
3519                 } else {
3520                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents extent vol 0x%x vno 0x%x foffset 0x%x:%x",
3521                               Fid.volume, Fid.vnode,
3522                               pExtent->FileOffset.HighPart,
3523                               pExtent->FileOffset.LowPart);
3524                     osi_Log2(afsd_logp, "... coffset 0x%x:%x UNKNOWN to redirector; owned by redirector",
3525                               pExtent->CacheOffset.HighPart,
3526                               pExtent->CacheOffset.LowPart);
3527                 }
3528                 buf_Release(bufp);
3529                 continue;
3530             }
3531
3532             if (pExtent->Flags & AFS_EXTENT_FLAG_IN_USE) {
3533                 osi_Log4(afsd_logp, "RDR_ReleaseFileExtents extent vol 0x%x vno 0x%x foffset 0x%x:%x",
3534                           Fid.volume, Fid.vnode,
3535                           pExtent->FileOffset.HighPart,
3536                           pExtent->FileOffset.LowPart);
3537                 osi_Log2(afsd_logp, "... coffset 0x%x:%x IN_USE by file system",
3538                           pExtent->CacheOffset.HighPart,
3539                           pExtent->CacheOffset.LowPart);
3540
3541                 /* Move the buffer to the front of the queue */
3542                 lock_ObtainWrite(&buf_globalLock);
3543                 buf_MoveToHeadOfRedirQueue(scp, bufp);
3544                 lock_ReleaseWrite(&buf_globalLock);
3545                 buf_Release(bufp);
3546                 continue;
3547             }
3548
3549             if (bufp->datap - RDR_extentBaseAddress == pExtent->CacheOffset.QuadPart) {
3550                 if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3551                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents extent vol 0x%x vno 0x%x foffset 0x%x:%x not held by file system",
3552                              Fid.volume, Fid.vnode, pExtent->FileOffset.HighPart,
3553                              pExtent->FileOffset.LowPart);
3554                     osi_Log2(afsd_logp, "... coffset 0x%x:%x",
3555                              pExtent->CacheOffset.HighPart,
3556                              pExtent->CacheOffset.LowPart);
3557                 } else {
3558                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents bufp 0x%p vno 0x%x foffset 0x%x:%x",
3559                               bufp, bufp->fid.vnode, pExtent->FileOffset.HighPart,
3560                               pExtent->FileOffset.LowPart);
3561                     osi_Log2(afsd_logp, "... coffset 0x%x:%x",
3562                              pExtent->CacheOffset.HighPart,
3563                              pExtent->CacheOffset.LowPart);
3564
3565                     if (pExtent->Flags || ReleaseExtentsCB->Flags) {
3566                         lock_ObtainMutex(&bufp->mx);
3567                         if ( (ReleaseExtentsCB->Flags & AFS_EXTENT_FLAG_RELEASE) ||
3568                              (pExtent->Flags & AFS_EXTENT_FLAG_RELEASE) )
3569                         {
3570                             if (bufp->qFlags & CM_BUF_QREDIR) {
3571                                 lock_ObtainWrite(&buf_globalLock);
3572                                 if (bufp->qFlags & CM_BUF_QREDIR) {
3573                                     buf_RemoveFromRedirQueue(scp, bufp);
3574                                     buf_ReleaseLocked(bufp, TRUE);
3575                                 }
3576                                 lock_ReleaseWrite(&buf_globalLock);
3577                             }
3578 #ifdef ODS_DEBUG
3579                             snprintf( dbgstr, 1024,
3580                                       "RDR_ReleaseFileExtents releasing: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3581                                       Fid.volume, Fid.vnode, Fid.unique,
3582                                       pExtent->FileOffset.HighPart,
3583                                       pExtent->FileOffset.LowPart,
3584                                       pExtent->CacheOffset.HighPart,
3585                                       pExtent->CacheOffset.LowPart);
3586                             OutputDebugStringA( dbgstr);
3587 #endif
3588                             released++;
3589                         } else {
3590 #ifdef ODS_DEBUG
3591                             snprintf( dbgstr, 1024,
3592                                       "RDR_ReleaseFileExtents not releasing: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3593                                       Fid.volume, Fid.vnode, Fid.unique,
3594                                       pExtent->FileOffset.HighPart,
3595                                       pExtent->FileOffset.LowPart,
3596                                       pExtent->CacheOffset.HighPart,
3597                                       pExtent->CacheOffset.LowPart);
3598                             OutputDebugStringA( dbgstr);
3599 #endif
3600                             osi_Log4( afsd_logp, "RDR_ReleaseFileExtents not releasing vol 0x%x vno 0x%x foffset 0x%x:%x",
3601                                       Fid.volume, Fid.vnode,
3602                                       pExtent->FileOffset.HighPart,
3603                                       pExtent->FileOffset.LowPart);
3604                             osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3605                                       pExtent->CacheOffset.HighPart,
3606                                       pExtent->CacheOffset.LowPart);
3607                         }
3608
3609                         if ( (ReleaseExtentsCB->Flags & AFS_EXTENT_FLAG_DIRTY) ||
3610                              (pExtent->Flags & AFS_EXTENT_FLAG_DIRTY) )
3611                         {
3612 #ifdef VALIDATE_CHECK_SUM
3613 #ifdef ODS_DEBUG
3614                             HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3615 #endif
3616
3617                             /*
3618                              * if the saved checksum matches the checksum of the current state of the buffer
3619                              * then the buffer is the same as what was given to the kernel.
3620                              */
3621                             if ( buf_ValidateCheckSum(bufp) ) {
3622                                 buf_ComputeCheckSum(bufp);
3623
3624                                 if (pExtent->Flags & AFS_EXTENT_FLAG_MD5_SET)
3625                                 {
3626 #ifdef ODS_DEBUG
3627                                     HexCheckSum(md5dbg2, sizeof(md5dbg2), pExtent->MD5);
3628                                     HexCheckSum(md5dbg3, sizeof(md5dbg3), bufp->md5cksum);
3629 #endif
3630                                     if (memcmp(bufp->md5cksum, pExtent->MD5, 16))
3631                                     {
3632 #ifdef ODS_DEBUG
3633                                         snprintf( dbgstr, 1024,
3634                                                   "RDR_ReleaseFileExtents dirty flag set but not dirty and user != kernel: old %s kernel %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3635                                                   md5dbg, md5dbg2,md5dbg3,
3636                                                   Fid.volume, Fid.vnode, Fid.unique,
3637                                                   pExtent->FileOffset.HighPart,
3638                                                   pExtent->FileOffset.LowPart,
3639                                                   pExtent->CacheOffset.HighPart,
3640                                                   pExtent->CacheOffset.LowPart);
3641                                         OutputDebugStringA( dbgstr);
3642 #endif
3643                                         osi_Log4( afsd_logp, "RDR_ReleaseFileExtents dirty flag set and checksums do not match! vol 0x%x vno 0x%x foffset 0x%x:%x",
3644                                                   Fid.volume, Fid.vnode,
3645                                                   pExtent->FileOffset.HighPart,
3646                                                   pExtent->FileOffset.LowPart);
3647                                         osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3648                                                   pExtent->CacheOffset.HighPart,
3649                                                   pExtent->CacheOffset.LowPart);
3650                                         buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
3651                                         dirty++;
3652                                     } else {
3653 #ifdef ODS_DEBUG
3654                                         snprintf( dbgstr, 1024,
3655                                                   "RDR_ReleaseFileExtents dirty flag set but not dirty and user == kernel: old %s kernel %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3656                                                   md5dbg, md5dbg2, md5dbg3,
3657                                                   Fid.volume, Fid.vnode, Fid.unique,
3658                                                   pExtent->FileOffset.HighPart,
3659                                                   pExtent->FileOffset.LowPart,
3660                                                   pExtent->CacheOffset.HighPart,
3661                                                   pExtent->CacheOffset.LowPart);
3662                                         OutputDebugStringA( dbgstr);
3663 #endif
3664                                         osi_Log4( afsd_logp, "RDR_ReleaseFileExtents dirty flag set but extent has not changed vol 0x%x vno 0x%x foffset 0x%x:%x",
3665                                                   Fid.volume, Fid.vnode,
3666                                                   pExtent->FileOffset.HighPart,
3667                                                   pExtent->FileOffset.LowPart);
3668                                         osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3669                                                   pExtent->CacheOffset.HighPart,
3670                                                   pExtent->CacheOffset.LowPart);
3671                                     }
3672                                 } else {
3673 #ifdef ODS_DEBUG
3674                                         snprintf( dbgstr, 1024,
3675                                                   "RDR_ReleaseFileExtents dirty flag set but not dirty: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3676                                                   Fid.volume, Fid.vnode, Fid.unique,
3677                                                   pExtent->FileOffset.HighPart,
3678                                                   pExtent->FileOffset.LowPart,
3679                                                   pExtent->CacheOffset.HighPart,
3680                                                   pExtent->CacheOffset.LowPart);
3681                                         OutputDebugStringA( dbgstr);
3682 #endif
3683                                         osi_Log4( afsd_logp, "RDR_ReleaseFileExtents dirty flag set but extent has not changed vol 0x%x vno 0x%x foffset 0x%x:%x",
3684                                                   Fid.volume, Fid.vnode,
3685                                                   pExtent->FileOffset.HighPart,
3686                                                   pExtent->FileOffset.LowPart);
3687                                         osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3688                                                   pExtent->CacheOffset.HighPart,
3689                                                   pExtent->CacheOffset.LowPart);
3690                                 }
3691                             } else {
3692                                 buf_ComputeCheckSum(bufp);
3693 #ifdef ODS_DEBUG
3694                                 if (pExtent->Flags & AFS_EXTENT_FLAG_MD5_SET)
3695                                 {
3696                                     HexCheckSum(md5dbg3, sizeof(md5dbg3), bufp->md5cksum);
3697                                     if (memcmp(bufp->md5cksum, pExtent->MD5, 16))
3698                                     {
3699                                         snprintf( dbgstr, 1024,
3700                                                   "RDR_ReleaseFileExtents dirty flag set and dirty and user != kernel: old %s kernel %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3701                                                   md5dbg, md5dbg2,md5dbg3,
3702                                                   Fid.volume, Fid.vnode, Fid.unique,
3703                                                   pExtent->FileOffset.HighPart,
3704                                                   pExtent->FileOffset.LowPart,
3705                                                   pExtent->CacheOffset.HighPart,
3706                                                   pExtent->CacheOffset.LowPart);
3707                                         OutputDebugStringA( dbgstr);
3708                                     } else {
3709                                         snprintf( dbgstr, 1024,
3710                                                   "RDR_ReleaseFileExtents dirty flag set and dirty and user == kernel: old %s kernel %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3711                                                   md5dbg, md5dbg2,md5dbg3,
3712                                                   Fid.volume, Fid.vnode, Fid.unique,
3713                                                   pExtent->FileOffset.HighPart,
3714                                                   pExtent->FileOffset.LowPart,
3715                                                   pExtent->CacheOffset.HighPart,
3716                                                   pExtent->CacheOffset.LowPart);
3717                                         OutputDebugStringA( dbgstr);
3718                                     }
3719                                 } else {
3720                                     snprintf( dbgstr, 1024,
3721                                               "RDR_ReleaseFileExtents dirty flag set: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3722                                               Fid.volume, Fid.vnode, Fid.unique,
3723                                               pExtent->FileOffset.HighPart,
3724                                               pExtent->FileOffset.LowPart,
3725                                               pExtent->CacheOffset.HighPart,
3726                                               pExtent->CacheOffset.LowPart);
3727                                     OutputDebugStringA( dbgstr);
3728                                 }
3729 #endif
3730                                 buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
3731                                 dirty++;
3732                             }
3733 #else /* !VALIDATE_CHECK_SUM */
3734                             buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
3735                             dirty++;
3736 #endif /* VALIDATE_CHECK_SUM */
3737                         }
3738 #ifdef VALIDATE_CHECK_SUM
3739                         else {
3740 #ifdef ODS_DEBUG
3741                             HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3742 #endif
3743                             if ( !buf_ValidateCheckSum(bufp) ) {
3744                                 buf_ComputeCheckSum(bufp);
3745 #ifdef ODS_DEBUG
3746                                 HexCheckSum(md5dbg3, sizeof(md5dbg2), bufp->md5cksum);
3747                                 snprintf( dbgstr, 1024,
3748                                           "RDR_ReleaseFileExtents dirty flag not set but dirty! old %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3749                                           md5dbg, md5dbg3,
3750                                           Fid.volume, Fid.vnode, Fid.unique,
3751                                           pExtent->FileOffset.HighPart,
3752                                           pExtent->FileOffset.LowPart,
3753                                           pExtent->CacheOffset.HighPart,
3754                                           pExtent->CacheOffset.LowPart);
3755                                 OutputDebugStringA( dbgstr);
3756 #endif
3757                                 osi_Log4( afsd_logp, "RDR_ReleaseFileExtents dirty flag not set but extent has changed vol 0x%x vno 0x%x foffset 0x%x:%x",
3758                                           Fid.volume, Fid.vnode,
3759                                           pExtent->FileOffset.HighPart,
3760                                           pExtent->FileOffset.LowPart);
3761                                 osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3762                                           pExtent->CacheOffset.HighPart,
3763                                           pExtent->CacheOffset.LowPart);
3764                                 buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
3765                                 dirty++;
3766                             } else {
3767                                 buf_ComputeCheckSum(bufp);
3768 #ifdef ODS_DEBUG
3769                                 HexCheckSum(md5dbg3, sizeof(md5dbg2), bufp->md5cksum);
3770                                 snprintf( dbgstr, 1024,
3771                                           "RDR_ReleaseFileExtents dirty flag not set: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3772                                           Fid.volume, Fid.vnode, Fid.unique,
3773                                           pExtent->FileOffset.HighPart,
3774                                           pExtent->FileOffset.LowPart,
3775                                           pExtent->CacheOffset.HighPart,
3776                                           pExtent->CacheOffset.LowPart);
3777                                 OutputDebugStringA( dbgstr);
3778 #endif
3779                                 osi_Log4( afsd_logp, "RDR_ReleaseFileExtents dirty flag not set: vol 0x%x vno 0x%x foffset 0x%x:%x",
3780                                           Fid.volume, Fid.vnode,
3781                                           pExtent->FileOffset.HighPart,
3782                                           pExtent->FileOffset.LowPart);
3783                                 osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3784                                           pExtent->CacheOffset.HighPart,
3785                                           pExtent->CacheOffset.LowPart);
3786                             }
3787                         }
3788 #endif /* VALIDATE_CHECK_SUM */
3789                         lock_ReleaseMutex(&bufp->mx);
3790                     }
3791                 }
3792             }
3793             else {
3794                 char * datap = RDR_extentBaseAddress + pExtent->CacheOffset.QuadPart;
3795                 cm_buf_t *wbp;
3796
3797                 for (wbp = cm_data.buf_allp; wbp; wbp = wbp->allp) {
3798                     if (wbp->datap == datap)
3799                         break;
3800                 }
3801
3802 #ifdef ODS_DEBUG
3803                 snprintf( dbgstr, 1024,
3804                           "RDR_ReleaseFileExtents non-matching extent vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3805                           Fid.volume, Fid.vnode, Fid.unique,
3806                           pExtent->FileOffset.HighPart,
3807                           pExtent->FileOffset.LowPart,
3808                           pExtent->CacheOffset.HighPart,
3809                           pExtent->CacheOffset.LowPart);
3810                 OutputDebugStringA( dbgstr);
3811 #endif
3812                 osi_Log4( afsd_logp, "RDR_ReleaseFileExtents non-matching extent vol 0x%x vno 0x%x foffset 0x%x:%x",
3813                           Fid.volume, Fid.vnode,
3814                           pExtent->FileOffset.HighPart,
3815                           pExtent->FileOffset.LowPart);
3816                 osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3817                           pExtent->CacheOffset.HighPart,
3818                           pExtent->CacheOffset.LowPart);
3819                 osi_Log5( afsd_logp, "... belongs to bp 0x%p vol 0x%x vno 0x%x foffset 0x%x:%x",
3820                           wbp, wbp->fid.volume, wbp->fid.vnode, wbp->offset.HighPart, wbp->offset.LowPart);
3821 #ifdef DEBUG
3822                 DebugBreak();
3823 #endif
3824             }
3825             buf_Release(bufp);
3826         }
3827         else {
3828             char * datap = RDR_extentBaseAddress + pExtent->CacheOffset.QuadPart;
3829             cm_buf_t *wbp;
3830
3831             for (wbp = cm_data.buf_allp; wbp; wbp = wbp->allp) {
3832                 if (wbp->datap == datap)
3833                     break;
3834             }
3835
3836 #ifdef ODS_DEBUG
3837             snprintf( dbgstr, 1024,
3838                       "RDR_ReleaseFileExtents unknown extent vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3839                       Fid.volume, Fid.vnode, Fid.unique,
3840                       pExtent->FileOffset.HighPart,
3841                       pExtent->FileOffset.LowPart,
3842                       pExtent->CacheOffset.HighPart,
3843                       pExtent->CacheOffset.LowPart);
3844             OutputDebugStringA( dbgstr);
3845 #endif
3846             osi_Log4( afsd_logp, "RDR_ReleaseFileExtents unknown extent vol 0x%x vno 0x%x foffset 0x%x:%x",
3847                       Fid.volume, Fid.vnode,
3848                       pExtent->FileOffset.HighPart,
3849                       pExtent->FileOffset.LowPart);
3850             osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3851                       pExtent->CacheOffset.HighPart,
3852                       pExtent->CacheOffset.LowPart);
3853             osi_Log5( afsd_logp, "... belongs to bp 0x%p vol 0x%x vno 0x%x foffset 0x%x:%x",
3854                       wbp, wbp->fid.volume, wbp->fid.vnode, wbp->offset.HighPart, wbp->offset.LowPart);
3855         }
3856     }
3857
3858     if (scp) {
3859         if (ReleaseExtentsCB->Flags & AFS_EXTENT_FLAG_FLUSH) {
3860             lock_ObtainWrite(&scp->rw);
3861             code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_WRITE,
3862                              CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3863             lock_ReleaseWrite(&scp->rw);
3864             if (code == 0)
3865                 code = cm_FSync(scp, userp, &req, FALSE);
3866         }
3867         else if (dirty) {
3868             osi_hyper_t offset = {0,0};
3869             afs_uint32  length = 0;
3870             afs_uint32  rights = 0;
3871
3872             lock_ObtainWrite(&scp->rw);
3873             code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_WRITE,
3874                              CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3875             lock_ReleaseWrite(&scp->rw);
3876             if (code == 0) {
3877                 /*
3878                  * there is at least one dirty extent on this file.  queue up background store
3879                  * requests for contiguous blocks
3880                  */
3881                 for ( count = 0; count < ReleaseExtentsCB->ExtentCount; count++) {
3882                     if (ReleaseExtentsCB->FileExtents[count].FileOffset.QuadPart == offset.QuadPart + length &&
3883                          length + cm_data.buf_blockSize <= cm_chunkSize)
3884                     {
3885                         length += cm_data.buf_blockSize;
3886                     } else {
3887                         if (!(offset.QuadPart == 0 && length == 0))
3888                             cm_QueueBKGRequest(scp, cm_BkgStore, offset.LowPart, offset.HighPart,
3889                                                 length, 0, userp, &req);
3890                         offset.QuadPart = ReleaseExtentsCB->FileExtents[count].FileOffset.QuadPart;
3891                         length = cm_data.buf_blockSize;
3892                     }
3893                 }
3894                 cm_QueueBKGRequest(scp, cm_BkgStore, offset.LowPart, offset.HighPart,
3895                                    length, 0, userp, &req);
3896             }
3897         }
3898         cm_ReleaseSCache(scp);
3899     }
3900
3901     osi_Log5(afsd_logp, "RDR_ReleaseFileExtents File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x Released %d",
3902               FileId.Cell, FileId.Volume,
3903               FileId.Vnode, FileId.Unique, released);
3904     if (code && code != CM_ERROR_WOULDBLOCK) {
3905         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3906         (*ResultCB)->ResultStatus = status;
3907         osi_Log2(afsd_logp, "RDR_ReleaseFileExtents FAILURE code=0x%x status=0x%x",
3908                   code, status);
3909     } else {
3910         (*ResultCB)->ResultStatus = 0;
3911         osi_Log0(afsd_logp, "RDR_ReleaseFileExtents SUCCESS");
3912     }
3913     (*ResultCB)->ResultBufferLength = 0;
3914
3915     return;
3916 }
3917
3918 DWORD
3919 RDR_ProcessReleaseFileExtentsResult( IN AFSReleaseFileExtentsResultCB *ReleaseFileExtentsResultCB,
3920                                      IN DWORD ResultBufferLength)
3921 {
3922     afs_uint32  code = 0;
3923     cm_req_t    req;
3924     osi_hyper_t thyper;
3925     cm_buf_t    *bufp;
3926     unsigned int fileno, extentno, total_extents = 0;
3927     AFSReleaseFileExtentsResultFileCB *pNextFileCB;
3928 #ifdef ODS_DEBUG
3929 #ifdef VALIDATE_CHECK_SUM
3930     char md5dbg[33], md5dbg2[33], md5dbg3[33];
3931 #endif
3932     char dbgstr[1024];
3933 #endif
3934     RDR_InitReq(&req, FALSE);
3935
3936     for ( fileno = 0, pNextFileCB = &ReleaseFileExtentsResultCB->Files[0];
3937           fileno < ReleaseFileExtentsResultCB->FileCount;
3938           fileno++ ) {
3939         AFSReleaseFileExtentsResultFileCB *pFileCB = pNextFileCB;
3940         cm_user_t       *userp = NULL;
3941         cm_fid_t         Fid;
3942         cm_scache_t *    scp = NULL;
3943         int              dirty = 0;
3944         int              released = 0;
3945         int              deleted = 0;
3946         char * p;
3947
3948         userp = RDR_UserFromAuthGroup( &pFileCB->AuthGroup);
3949
3950         osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult %d.%d.%d.%d",
3951                   pFileCB->FileId.Cell, pFileCB->FileId.Volume,
3952                   pFileCB->FileId.Vnode, pFileCB->FileId.Unique);
3953
3954         /* Process the release */
3955         Fid.cell = pFileCB->FileId.Cell;
3956         Fid.volume = pFileCB->FileId.Volume;
3957         Fid.vnode = pFileCB->FileId.Vnode;
3958         Fid.unique = pFileCB->FileId.Unique;
3959         Fid.hash = pFileCB->FileId.Hash;
3960
3961         if (Fid.cell == 0) {
3962             osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult Invalid FID %d.%d.%d.%d",
3963                      Fid.cell, Fid.volume, Fid.vnode, Fid.unique);
3964             code = CM_ERROR_INVAL;
3965             goto cleanup_file;
3966         }
3967
3968         code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3969         if (code) {
3970             osi_Log1(afsd_logp, "RDR_ProcessReleaseFileExtentsResult cm_GetSCache FID failure code=0x%x",
3971                      code);
3972             /*
3973              * A failure to find the cm_scache object cannot prevent the service
3974              * from accepting the extents back from the redirector.
3975              */
3976         }
3977
3978         deleted = scp && (scp->flags & CM_SCACHEFLAG_DELETED);
3979
3980         /* if the scp was not found, do not perform the length check */
3981         if (scp && (pFileCB->AllocationSize.QuadPart != scp->length.QuadPart)) {
3982             cm_attr_t setAttr;
3983
3984             memset(&setAttr, 0, sizeof(cm_attr_t));
3985             lock_ObtainWrite(&scp->rw);
3986             if (pFileCB->AllocationSize.QuadPart != scp->length.QuadPart) {
3987                 osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult length change vol 0x%x vno 0x%x length 0x%x:%x",
3988                           scp->fid.volume, scp->fid.vnode,
3989                           pFileCB->AllocationSize.HighPart,
3990                           pFileCB->AllocationSize.LowPart);
3991                 setAttr.mask |= CM_ATTRMASK_LENGTH;
3992                 setAttr.length.LowPart = pFileCB->AllocationSize.LowPart;
3993                 setAttr.length.HighPart = pFileCB->AllocationSize.HighPart;
3994             }
3995             lock_ReleaseWrite(&scp->rw);
3996             if (setAttr.mask)
3997                 code = cm_SetAttr(scp, &setAttr, userp, &req);
3998         }
3999
4000         for ( extentno = 0; extentno < pFileCB->ExtentCount; total_extents++, extentno++ ) {
4001             AFSFileExtentCB *pExtent = &pFileCB->FileExtents[extentno];
4002
4003             thyper.QuadPart = pExtent->FileOffset.QuadPart;
4004
4005             bufp = buf_Find(&Fid, &thyper);
4006             if (bufp) {
4007                 if (pExtent->Flags & AFS_EXTENT_FLAG_UNKNOWN) {
4008                     if (!(bufp->qFlags & CM_BUF_QREDIR)) {
4009                         osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4010                                  Fid.volume, Fid.vnode,
4011                                  pExtent->FileOffset.HighPart,
4012                                  pExtent->FileOffset.LowPart);
4013                         osi_Log2(afsd_logp, "... coffset 0x%x:%x UNKNOWN to redirector; previously released",
4014                                  pExtent->CacheOffset.HighPart,
4015                                  pExtent->CacheOffset.LowPart);
4016                     } else {
4017                         osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4018                                  Fid.volume, Fid.vnode,
4019                                  pExtent->FileOffset.HighPart,
4020                                  pExtent->FileOffset.LowPart);
4021                         osi_Log2(afsd_logp, "... coffset 0x%x:%x UNKNOWN to redirector; owned by redirector",
4022                                  pExtent->CacheOffset.HighPart,
4023                                  pExtent->CacheOffset.LowPart);
4024                     }
4025                     buf_Release(bufp);
4026                     continue;
4027                 }
4028
4029                 if (pExtent->Flags & AFS_EXTENT_FLAG_IN_USE) {
4030                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4031                               Fid.volume, Fid.vnode,
4032                               pExtent->FileOffset.HighPart,
4033                               pExtent->FileOffset.LowPart);
4034                     osi_Log2(afsd_logp, "... coffset 0x%x:%x IN_USE by file system",
4035                               pExtent->CacheOffset.HighPart,
4036                               pExtent->CacheOffset.LowPart);
4037
4038                     /* Move the buffer to the front of the queue */
4039                     lock_ObtainWrite(&buf_globalLock);
4040                     buf_MoveToHeadOfRedirQueue(scp, bufp);
4041                     lock_ReleaseWrite(&buf_globalLock);
4042                     buf_Release(bufp);
4043                     continue;
4044                 }
4045
4046                 if (bufp->datap - RDR_extentBaseAddress == pExtent->CacheOffset.QuadPart) {
4047                     if (!(bufp->qFlags & CM_BUF_QREDIR)) {
4048                         osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4049                                  Fid.volume, Fid.vnode,
4050                                  pExtent->FileOffset.HighPart,
4051                                  pExtent->FileOffset.LowPart);
4052                         osi_Log2(afsd_logp, "... coffset 0x%x:%x not held by file system",
4053                                  pExtent->CacheOffset.HighPart,
4054                                  pExtent->CacheOffset.LowPart);
4055 #ifdef ODS_DEBUG
4056                         snprintf(dbgstr, 1024,
4057                                   "RDR_ProcessReleaseFileExtentsResult not held by redirector! flags 0x%x:%x vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4058                                   ReleaseFileExtentsResultCB->Flags, pExtent->Flags,
4059                                   Fid.volume, Fid.vnode, Fid.unique,
4060                                   pExtent->FileOffset.HighPart,
4061                                   pExtent->FileOffset.LowPart,
4062                                   pExtent->CacheOffset.HighPart,
4063                                   pExtent->CacheOffset.LowPart);
4064                         OutputDebugStringA( dbgstr);
4065 #endif
4066                     } else {
4067                         osi_Log5(afsd_logp, "RDR_ProcessReleaseFileExtentsResult bufp 0x%p foffset 0x%x:%x coffset 0x%x:%x",
4068                                  bufp, pExtent->FileOffset.HighPart, pExtent->FileOffset.LowPart,
4069                                  pExtent->CacheOffset.HighPart, pExtent->CacheOffset.LowPart);
4070
4071                         if (pExtent->Flags || ReleaseFileExtentsResultCB->Flags) {
4072                             lock_ObtainMutex(&bufp->mx);
4073                             if ( (ReleaseFileExtentsResultCB->Flags & AFS_EXTENT_FLAG_RELEASE) ||
4074                                  (pExtent->Flags & AFS_EXTENT_FLAG_RELEASE) )
4075                             {
4076                                 if (bufp->qFlags & CM_BUF_QREDIR) {
4077                                     lock_ObtainWrite(&buf_globalLock);
4078                                     if (bufp->qFlags & CM_BUF_QREDIR) {
4079                                         buf_RemoveFromRedirQueue(scp, bufp);
4080                                         buf_ReleaseLocked(bufp, TRUE);
4081                                     }
4082                                     lock_ReleaseWrite(&buf_globalLock);
4083                                 }
4084
4085 #ifdef ODS_DEBUG
4086                                 snprintf(dbgstr, 1024,
4087                                           "RDR_ProcessReleaseFileExtentsResult extent released: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4088                                           Fid.volume, Fid.vnode, Fid.unique,
4089                                           pExtent->FileOffset.HighPart,
4090                                           pExtent->FileOffset.LowPart,
4091                                           pExtent->CacheOffset.HighPart,
4092                                           pExtent->CacheOffset.LowPart);
4093                                 OutputDebugStringA( dbgstr);
4094 #endif
4095
4096                                 released++;
4097                             } else {
4098                                 osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult not releasing vol 0x%x vno 0x%x foffset 0x%x:%x",
4099                                          Fid.volume, Fid.vnode,
4100                                          pExtent->FileOffset.HighPart,
4101                                          pExtent->FileOffset.LowPart);
4102                                 osi_Log2(afsd_logp, "... coffset 0x%x:%x",
4103                                          pExtent->CacheOffset.HighPart,
4104                                          pExtent->CacheOffset.LowPart);
4105 #ifdef ODS_DEBUG
4106                                 snprintf(dbgstr, 1024,
4107                                           "RDR_ProcessReleaseFileExtentsResult not released! vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4108                                           Fid.volume, Fid.vnode, Fid.unique,
4109                                           pExtent->FileOffset.HighPart,
4110                                           pExtent->FileOffset.LowPart,
4111                                           pExtent->CacheOffset.HighPart,
4112                                           pExtent->CacheOffset.LowPart);
4113                                 OutputDebugStringA( dbgstr);
4114 #endif
4115                             }
4116
4117                             if ((ReleaseFileExtentsResultCB->Flags & AFS_EXTENT_FLAG_DIRTY) ||
4118                                 (pExtent->Flags & AFS_EXTENT_FLAG_DIRTY))
4119                             {
4120 #ifdef VALIDATE_CHECK_SUM
4121                                 if ( buf_ValidateCheckSum(bufp) ) {
4122 #ifdef ODS_DEBUG
4123                                     HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
4124                                     if (ReleaseFileExtentsResultCB->Flags & AFS_EXTENT_FLAG_MD5_SET)
4125                                         HexCheckSum(md5dbg2, sizeof(md5dbg2), pExtent->MD5);
4126 #endif
4127                                     buf_ComputeCheckSum(bufp);
4128 #ifdef ODS_DEBUG
4129                                     HexCheckSum(md5dbg3, sizeof(md5dbg), bufp->md5cksum);
4130 #endif
4131                                     if (ReleaseFileExtentsResultCB->Flags & AFS_EXTENT_FLAG_MD5_SET)
4132                                     {
4133                                         if (memcmp(bufp->md5cksum, pExtent->MD5, 16))
4134                                         {
4135 #ifdef ODS_DEBUG
4136                                             snprintf(dbgstr, 1024,
4137                                                       "RDR_ProcessReleaseFileExtentsResult dirty flag set and checksums do not match! user %s kernel %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4138                                                       md5dbg3, md5dbg2,
4139                                                       Fid.volume, Fid.vnode, Fid.unique,
4140                                                       pExtent->FileOffset.HighPart,
4141                                                       pExtent->FileOffset.LowPart,
4142                                                       pExtent->CacheOffset.HighPart,
4143                                                       pExtent->CacheOffset.LowPart);
4144                                             OutputDebugStringA( dbgstr);
4145 #endif
4146                                             osi_Log4(afsd_logp,
4147                                                       "RDR_ProcessReleaseFileExtentsResult dirty flag set and checksums do not match! vol 0x%x vno 0x%x foffset 0x%x:%x",
4148                                                       Fid.volume, Fid.vnode,
4149                                                       pExtent->FileOffset.HighPart,
4150                                                       pExtent->FileOffset.LowPart);
4151                                             osi_Log2(afsd_logp,
4152                                                       "... coffset 0x%x:%x",
4153                                                       pExtent->CacheOffset.HighPart,
4154                                                       pExtent->CacheOffset.LowPart);
4155
4156                                             if (!deleted) {
4157                                                 buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
4158                                                 dirty++;
4159                                             }
4160                                         } else {
4161 #ifdef ODS_DEBUG
4162                                             snprintf(dbgstr, 1024,
4163                                                       "RDR_ProcessReleaseFileExtentsResult dirty flag set but extent has not changed! old %s kernel %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4164                                                       md5dbg, md5dbg2, md5dbg3,
4165                                                       Fid.volume, Fid.vnode, Fid.unique,
4166                                                       pExtent->FileOffset.HighPart,
4167                                                       pExtent->FileOffset.LowPart,
4168                                                       pExtent->CacheOffset.HighPart,
4169                                                       pExtent->CacheOffset.LowPart);
4170                                             OutputDebugStringA( dbgstr);
4171 #endif
4172                                             osi_Log4(afsd_logp,
4173                                                       "RDR_ProcessReleaseFileExtentsResult dirty flag set but extent has not changed vol 0x%x vno 0x%x foffset 0x%x:%x",
4174                                                       Fid.volume, Fid.vnode,
4175                                                       pExtent->FileOffset.HighPart,
4176                                                       pExtent->FileOffset.LowPart);
4177                                             osi_Log2(afsd_logp,
4178                                                       "... coffset 0x%x:%x",
4179                                                       pExtent->CacheOffset.HighPart,
4180                                                       pExtent->CacheOffset.LowPart);
4181                                         }
4182                                     }
4183                                 }
4184 #else /* !VALIDATE_CHECK_SUM */
4185                                 if (!deleted) {
4186                                     buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
4187                                     dirty++;
4188                                 }
4189 #ifdef ODS_DEBUG
4190                                 snprintf(dbgstr, 1024,
4191                                           "RDR_ProcessReleaseFileExtentsResult dirty! vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4192                                           Fid.volume, Fid.vnode, Fid.unique,
4193                                           pExtent->FileOffset.HighPart,
4194                                           pExtent->FileOffset.LowPart,
4195                                           pExtent->CacheOffset.HighPart,
4196                                           pExtent->CacheOffset.LowPart);
4197                                 OutputDebugStringA( dbgstr);
4198 #endif
4199 #endif /* VALIDATE_CHECK_SUM */
4200                             }
4201 #ifdef VALIDATE_CHECK_SUM
4202                             else {
4203 #ifdef ODS_DEBUG
4204                                 HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
4205 #endif
4206                                 if (!buf_ValidateCheckSum(bufp) ) {
4207                                     buf_ComputeCheckSum(bufp);
4208 #ifdef ODS_DEBUG
4209                                     HexCheckSum(md5dbg3, sizeof(md5dbg2), bufp->md5cksum);
4210                                     snprintf(dbgstr, 1024,
4211                                              "RDR_ProcessReleaseFileExtentsResult dirty flag not set but dirty! old %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4212                                              md5dbg, md5dbg3,
4213                                              Fid.volume, Fid.vnode, Fid.unique,
4214                                              pExtent->FileOffset.HighPart,
4215                                              pExtent->FileOffset.LowPart,
4216                                              pExtent->CacheOffset.HighPart,
4217                                              pExtent->CacheOffset.LowPart);
4218                                     OutputDebugStringA( dbgstr);
4219 #endif
4220                                     osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult dirty flag NOT set but extent has changed! vol 0x%x vno 0x%x foffset 0x%x:%x",
4221                                              Fid.volume, Fid.vnode,
4222                                              pExtent->FileOffset.HighPart,
4223                                              pExtent->FileOffset.LowPart);
4224                                     osi_Log2(afsd_logp, "... coffset 0x%x:%x",
4225                                              pExtent->CacheOffset.HighPart,
4226                                              pExtent->CacheOffset.LowPart);
4227 #ifdef DEBUG
4228                                     DebugBreak();
4229 #endif
4230                                     if (!deleted) {
4231                                         buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
4232                                         dirty++;
4233                                     }
4234                                 } else {
4235                                     buf_ComputeCheckSum(bufp);
4236 #ifdef ODS_DEBUG
4237                                     HexCheckSum(md5dbg3, sizeof(md5dbg2), bufp->md5cksum);
4238                                     snprintf(dbgstr, 1024,
4239                                              "RDR_ProcessReleaseFileExtentsResult dirty flag not set and not dirty! old %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4240                                              md5dbg, md5dbg3,
4241                                              Fid.volume, Fid.vnode, Fid.unique,
4242                                              pExtent->FileOffset.HighPart,
4243                                              pExtent->FileOffset.LowPart,
4244                                              pExtent->CacheOffset.HighPart,
4245                                              pExtent->CacheOffset.LowPart);
4246                                     OutputDebugStringA( dbgstr);
4247 #endif
4248                                 }
4249                             }
4250 #endif /* VALIDATE_CHECK_SUM */
4251                             lock_ReleaseMutex(&bufp->mx);
4252                         }
4253                     }
4254                 } else {
4255                     /* CacheOffset doesn't match bufp->datap */
4256                     char * datap = RDR_extentBaseAddress + pExtent->CacheOffset.QuadPart;
4257                     cm_buf_t *wbp;
4258
4259                     for (wbp = cm_data.buf_allp; wbp; wbp = wbp->allp) {
4260                         if (wbp->datap == datap)
4261                             break;
4262                     }
4263
4264 #ifdef ODS_DEBUG
4265                     snprintf(dbgstr, 1024,
4266                              "RDR_ProcessReleaseFileExtentsResult non-matching extent vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x flags 0x%x\n",
4267                              Fid.volume, Fid.vnode, Fid.unique,
4268                              pExtent->FileOffset.HighPart,
4269                              pExtent->FileOffset.LowPart,
4270                              pExtent->CacheOffset.HighPart,
4271                              pExtent->CacheOffset.LowPart,
4272                              pExtent->Flags);
4273                     OutputDebugStringA( dbgstr);
4274 #endif
4275                     osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult non-matching extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4276                              Fid.volume, Fid.vnode,
4277                              pExtent->FileOffset.HighPart,
4278                              pExtent->FileOffset.LowPart);
4279                     osi_Log3(afsd_logp, "... coffset 0x%x:%x flags 0x%x",
4280                              pExtent->CacheOffset.HighPart,
4281                              pExtent->CacheOffset.LowPart,
4282                              pExtent->Flags);
4283                     if (wbp)
4284                         osi_Log5(afsd_logp, "... coffset belongs to bp 0x%p vol 0x%x vno 0x%x foffset 0x%x:%x",
4285                                  wbp, wbp->fid.volume, wbp->fid.vnode, wbp->offset.HighPart, wbp->offset.LowPart);
4286                     else
4287                         osi_Log0(afsd_logp, "... coffset cannot be found");
4288 #ifdef DEBUG
4289                     DebugBreak();
4290 #endif
4291                 }
4292                 buf_Release(bufp);
4293             } else {
4294                 if (pExtent->Flags & AFS_EXTENT_FLAG_UNKNOWN) {
4295                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4296                              Fid.volume, Fid.vnode, pExtent->FileOffset.HighPart,
4297                              pExtent->FileOffset.LowPart);
4298                     osi_Log2(afsd_logp, "... coffset 0x%x:%x UNKNOWN to redirector; cm_buf not found -- recycled?",
4299                              pExtent->CacheOffset.HighPart,
4300                              pExtent->CacheOffset.LowPart);
4301
4302                     continue;
4303                 }
4304
4305 #ifdef ODS_DEBUG
4306                 snprintf(dbgstr, 1024,
4307                          "RDR_ProcessReleaseFileExtentsResult buf not found vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4308                          Fid.volume, Fid.vnode, Fid.unique,
4309                          pExtent->FileOffset.HighPart,
4310                          pExtent->FileOffset.LowPart,
4311                          pExtent->CacheOffset.HighPart,
4312                          pExtent->CacheOffset.LowPart);
4313                 OutputDebugStringA( dbgstr);
4314 #endif
4315                 osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult buf not found vol 0x%x vno 0x%x foffset 0x%x:%x",
4316                          Fid.volume, Fid.vnode,
4317                          pExtent->FileOffset.HighPart,
4318                          pExtent->FileOffset.LowPart);
4319                 osi_Log2(afsd_logp, "... coffset 0x%x:%x",
4320                          pExtent->CacheOffset.HighPart,
4321                          pExtent->CacheOffset.LowPart);
4322             }
4323         }
4324
4325         if (scp && dirty) {
4326             osi_hyper_t offset = {0,0};
4327             afs_uint32  length = 0;
4328
4329             /*
4330              * there is at least one dirty extent on this file.  queue up background store
4331              * requests for contiguous blocks
4332              */
4333             for ( extentno = 0; extentno < pFileCB->ExtentCount; extentno++ ) {
4334                 AFSFileExtentCB *pExtent = &pFileCB->FileExtents[extentno];
4335                 if (pExtent->FileOffset.QuadPart == offset.QuadPart + length &&
4336                      length < cm_chunkSize) {
4337                     length += cm_data.buf_blockSize;
4338                 } else {
4339                     if (!(offset.QuadPart == 0 && length == 0))
4340                         cm_QueueBKGRequest(scp, cm_BkgStore, offset.LowPart, offset.HighPart,
4341                                             length, 0, userp, &req);
4342                     offset.QuadPart = pExtent->FileOffset.QuadPart;
4343                     length = cm_data.buf_blockSize;
4344                 }
4345             }
4346             cm_QueueBKGRequest(scp, cm_BkgStore, offset.LowPart, offset.HighPart,
4347                                 length, 0, userp, &req);
4348         }
4349
4350         osi_Log5(afsd_logp, "RDR_ProcessReleaseFileExtentsResult File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x Released %d",
4351                   Fid.cell, Fid.volume, Fid.vnode, Fid.unique, released);
4352
4353       cleanup_file:
4354         if (userp)
4355             cm_ReleaseUser(userp);
4356         if (scp)
4357             cm_ReleaseSCache(scp);
4358
4359         p = (char *)pFileCB;
4360         p += sizeof(AFSReleaseFileExtentsResultFileCB);
4361         p += sizeof(AFSFileExtentCB) * (pFileCB->ExtentCount - 1);
4362         pNextFileCB = (AFSReleaseFileExtentsResultFileCB *)p;
4363     }
4364
4365     if (total_extents == 0) {
4366         osi_Log0(afsd_logp, "RDR_ProcessReleaseFileExtentsResult is empty");
4367         code = CM_ERROR_RETRY;
4368     }
4369
4370     if (code)
4371         osi_Log1(afsd_logp, "RDR_ProcessReleaseFileExtentsResult FAILURE code=0x%x", code);
4372     else
4373         osi_Log1(afsd_logp, "RDR_ProcessReleaseFileExtentsResult DONE code=0x%x", code);
4374
4375     return code;
4376 }
4377
4378 DWORD
4379 RDR_ReleaseFailedSetFileExtents( IN cm_user_t *userp,
4380                                  IN AFSSetFileExtentsCB *SetFileExtentsResultCB,
4381                                  IN DWORD ResultBufferLength)
4382 {
4383     afs_uint32  code = 0;
4384     cm_req_t    req;
4385     unsigned int extentno;
4386     cm_fid_t         Fid;
4387     cm_scache_t *    scp = NULL;
4388     int              dirty = 0;
4389
4390     RDR_InitReq(&req, FALSE);
4391
4392     osi_Log4(afsd_logp, "RDR_ReleaseFailedSetFileExtents %d.%d.%d.%d",
4393               SetFileExtentsResultCB->FileId.Cell, SetFileExtentsResultCB->FileId.Volume,
4394               SetFileExtentsResultCB->FileId.Vnode, SetFileExtentsResultCB->FileId.Unique);
4395
4396     /* Process the release */
4397     Fid.cell = SetFileExtentsResultCB->FileId.Cell;
4398     Fid.volume = SetFileExtentsResultCB->FileId.Volume;
4399     Fid.vnode = SetFileExtentsResultCB->FileId.Vnode;
4400     Fid.unique = SetFileExtentsResultCB->FileId.Unique;
4401     Fid.hash = SetFileExtentsResultCB->FileId.Hash;
4402
4403     if (Fid.cell == 0) {
4404         osi_Log4(afsd_logp, "RDR_ReleaseFailedSetFile Invalid FID %d.%d.%d.%d",
4405                   Fid.cell, Fid.volume, Fid.vnode, Fid.unique);
4406         code = CM_ERROR_INVAL;
4407         goto cleanup_file;
4408     }
4409
4410     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
4411     if (code) {
4412         osi_Log1(afsd_logp, "RDR_ReleaseFailedSetFileExtents cm_GetSCache FID failure code=0x%x",
4413                   code);
4414         /* Failure to find the cm_scache object cannot block return of the extents */
4415     }
4416
4417     for ( extentno = 0; extentno < SetFileExtentsResultCB->ExtentCount; extentno++ ) {
4418         osi_hyper_t thyper;
4419         cm_buf_t    *bufp;
4420         AFSFileExtentCB *pExtent = &SetFileExtentsResultCB->FileExtents[extentno];
4421
4422         thyper.QuadPart = pExtent->FileOffset.QuadPart;
4423
4424         bufp = buf_Find(&Fid, &thyper);
4425         if (bufp) {
4426             osi_Log5(afsd_logp, "RDR_ReleaseFailedSetFileExtents bufp 0x%p foffset 0x%x:%x coffset 0x%x:%x",
4427                       bufp, pExtent->FileOffset.HighPart, pExtent->FileOffset.LowPart,
4428                       pExtent->CacheOffset.HighPart, pExtent->CacheOffset.LowPart);
4429
4430             lock_ObtainMutex(&bufp->mx);
4431             if (bufp->qFlags & CM_BUF_QREDIR) {
4432                 lock_ObtainWrite(&buf_globalLock);
4433                 if (bufp->qFlags & CM_BUF_QREDIR) {
4434                     buf_RemoveFromRedirQueue(scp, bufp);
4435                     buf_ReleaseLocked(bufp, TRUE);
4436                 }
4437                 lock_ReleaseWrite(&buf_globalLock);
4438             }
4439             lock_ReleaseMutex(&bufp->mx);
4440             buf_Release(bufp);
4441         }
4442     }
4443
4444   cleanup_file:
4445     if (userp)
4446         cm_ReleaseUser(userp);
4447     if (scp)
4448         cm_ReleaseSCache(scp);
4449
4450     osi_Log1(afsd_logp, "RDR_ReleaseFailedSetFileExtents DONE code=0x%x", code);
4451     return code;
4452 }
4453
4454 void
4455 RDR_PioctlOpen( IN cm_user_t *userp,
4456                 IN AFSFileID  ParentId,
4457                 IN AFSPIOCtlOpenCloseRequestCB *pPioctlCB,
4458                 IN BOOL bWow64,
4459                 IN DWORD ResultBufferLength,
4460                 IN OUT AFSCommResult **ResultCB)
4461 {
4462     cm_fid_t    ParentFid;
4463     cm_fid_t    RootFid;
4464     cm_req_t    req;
4465
4466     RDR_InitReq(&req, bWow64);
4467
4468     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
4469     if (!(*ResultCB))
4470         return;
4471
4472     memset( *ResultCB,
4473             '\0',
4474             sizeof( AFSCommResult));
4475
4476     /* Get the active directory */
4477     ParentFid.cell = ParentId.Cell;
4478     ParentFid.volume = ParentId.Volume;
4479     ParentFid.vnode = ParentId.Vnode;
4480     ParentFid.unique = ParentId.Unique;
4481     ParentFid.hash = ParentId.Hash;
4482
4483     /* Get the root directory */
4484     RootFid.cell = pPioctlCB->RootId.Cell;
4485     RootFid.volume = pPioctlCB->RootId.Volume;
4486     RootFid.vnode = pPioctlCB->RootId.Vnode;
4487     RootFid.unique = pPioctlCB->RootId.Unique;
4488     RootFid.hash = pPioctlCB->RootId.Hash;
4489
4490     /* Create the pioctl index */
4491     RDR_SetupIoctl(pPioctlCB->RequestId, &ParentFid, &RootFid, userp, &req);
4492
4493     return;
4494 }
4495
4496
4497 void
4498 RDR_PioctlClose( IN cm_user_t *userp,
4499                  IN AFSFileID  ParentId,
4500                  IN AFSPIOCtlOpenCloseRequestCB *pPioctlCB,
4501                  IN BOOL bWow64,
4502                  IN DWORD ResultBufferLength,
4503                  IN OUT AFSCommResult **ResultCB)
4504 {
4505     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
4506     if (!(*ResultCB))
4507         return;
4508
4509     memset( *ResultCB,
4510             '\0',
4511             sizeof( AFSCommResult));
4512
4513     /* Cleanup the pioctl index */
4514     RDR_CleanupIoctl(pPioctlCB->RequestId);
4515
4516     return;
4517 }
4518
4519
4520 void
4521 RDR_PioctlWrite( IN cm_user_t *userp,
4522                  IN AFSFileID  ParentId,
4523                  IN AFSPIOCtlIORequestCB *pPioctlCB,
4524                  IN BOOL bWow64,
4525                  IN DWORD ResultBufferLength,
4526                  IN OUT AFSCommResult **ResultCB)
4527 {
4528     AFSPIOCtlIOResultCB *pResultCB;
4529     cm_scache_t *dscp = NULL;
4530     afs_uint32  code;
4531     cm_req_t    req;
4532     DWORD       status;
4533
4534     RDR_InitReq(&req, bWow64);
4535
4536     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof(AFSPIOCtlIOResultCB));
4537     if (!(*ResultCB))
4538         return;
4539
4540     memset( *ResultCB,
4541             '\0',
4542             sizeof( AFSCommResult) + sizeof(AFSPIOCtlIOResultCB));
4543
4544     pResultCB = (AFSPIOCtlIOResultCB *)(*ResultCB)->ResultData;
4545
4546     code = RDR_IoctlWrite(userp, pPioctlCB->RequestId, pPioctlCB->BufferLength, pPioctlCB->MappedBuffer);
4547     if (code) {
4548         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4549         (*ResultCB)->ResultStatus = status;
4550         return;
4551     }
4552
4553     pResultCB->BytesProcessed = pPioctlCB->BufferLength;
4554     (*ResultCB)->ResultBufferLength = sizeof( AFSPIOCtlIOResultCB);
4555 }
4556
4557 void
4558 RDR_PioctlRead( IN cm_user_t *userp,
4559                 IN AFSFileID  ParentId,
4560                 IN AFSPIOCtlIORequestCB *pPioctlCB,
4561                 IN BOOL bWow64,
4562                 IN BOOL bIsLocalSystem,
4563                 IN DWORD ResultBufferLength,
4564                 IN OUT AFSCommResult **ResultCB)
4565 {
4566     AFSPIOCtlIOResultCB *pResultCB;
4567     cm_scache_t *dscp = NULL;
4568     afs_uint32  code;
4569     cm_req_t    req;
4570     DWORD       status;
4571     afs_uint32  pflags = (bIsLocalSystem ? AFSCALL_FLAG_LOCAL_SYSTEM : 0);
4572
4573     RDR_InitReq(&req, bWow64);
4574
4575     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof(AFSPIOCtlIOResultCB));
4576     if (!(*ResultCB))
4577         return;
4578
4579     memset( *ResultCB,
4580             '\0',
4581             sizeof( AFSCommResult) + sizeof(AFSPIOCtlIOResultCB));
4582
4583     pResultCB = (AFSPIOCtlIOResultCB *)(*ResultCB)->ResultData;
4584
4585     code = RDR_IoctlRead(userp, pPioctlCB->RequestId, pPioctlCB->BufferLength, pPioctlCB->MappedBuffer,
4586                          &pResultCB->BytesProcessed, pflags);
4587     if (code) {
4588         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4589         (*ResultCB)->ResultStatus = status;
4590         return;
4591     }
4592
4593     (*ResultCB)->ResultBufferLength = sizeof( AFSPIOCtlIOResultCB);
4594 }
4595
4596 void
4597 RDR_ByteRangeLockSync( IN cm_user_t     *userp,
4598                        IN AFSFileID     FileId,
4599                        IN AFSByteRangeLockRequestCB *pBRLRequestCB,
4600                        IN BOOL bWow64,
4601                        IN DWORD ResultBufferLength,
4602                        IN OUT AFSCommResult **ResultCB)
4603 {
4604     AFSByteRangeLockResultCB *pResultCB = NULL;
4605     LARGE_INTEGER ProcessId;
4606     DWORD       Length;
4607     cm_scache_t *scp = NULL;
4608     cm_fid_t    Fid;
4609     afs_uint32  code;
4610     cm_req_t    req;
4611     cm_key_t    key;
4612     DWORD       i;
4613     DWORD       status;
4614
4615     ProcessId.QuadPart = pBRLRequestCB->ProcessId;
4616
4617     RDR_InitReq(&req, bWow64);
4618
4619     osi_Log4(afsd_logp, "RDR_ByteRangeLockSync File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
4620               FileId.Cell, FileId.Volume,
4621               FileId.Vnode, FileId.Unique);
4622     osi_Log2(afsd_logp, "... ProcessId 0x%x:%x",
4623              ProcessId.HighPart, ProcessId.LowPart);
4624
4625     Length = sizeof( AFSByteRangeLockResultCB) + ((pBRLRequestCB->Count - 1) * sizeof(AFSByteRangeLockResult));
4626     if (Length > ResultBufferLength) {
4627         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult));
4628         if (!(*ResultCB))
4629             return;
4630         memset( *ResultCB, 0, sizeof(AFSCommResult));
4631         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
4632         return;
4633     }
4634
4635     *ResultCB = (AFSCommResult *)malloc( Length + sizeof( AFSCommResult) );
4636     if (!(*ResultCB))
4637         return;
4638     memset( *ResultCB, '\0', Length + sizeof( AFSCommResult) );
4639     (*ResultCB)->ResultBufferLength = Length;
4640
4641     pResultCB = (AFSByteRangeLockResultCB *)(*ResultCB)->ResultData;
4642     pResultCB->FileId = FileId;
4643     pResultCB->Count = pBRLRequestCB->Count;
4644
4645     /* Allocate the extents from the buffer package */
4646     Fid.cell = FileId.Cell;
4647     Fid.volume = FileId.Volume;
4648     Fid.vnode = FileId.Vnode;
4649     Fid.unique = FileId.Unique;
4650     Fid.hash = FileId.Hash;
4651
4652     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
4653     if (code) {
4654         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4655         (*ResultCB)->ResultStatus = status;
4656         (*ResultCB)->ResultBufferLength = 0;
4657         osi_Log2(afsd_logp, "RDR_ByteRangeLockSync cm_GetSCache FID failure code=0x%x status=0x%x",
4658                   code, status);
4659         return;
4660     }
4661
4662     lock_ObtainWrite(&scp->rw);
4663
4664     /* start by looking up the file's end */
4665     code = cm_SyncOp(scp, NULL, userp, &req, 0,
4666                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4667     if (code) {
4668         lock_ReleaseWrite(&scp->rw);
4669         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4670         (*ResultCB)->ResultStatus = status;
4671         (*ResultCB)->ResultBufferLength = 0;
4672         osi_Log3(afsd_logp, "RDR_ByteRangeLockSync cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
4673                  scp, code, status);
4674         return;
4675     }
4676
4677     /* the scp is now locked and current */
4678     key = cm_GenerateKey(CM_SESSION_IFS, ProcessId.QuadPart, 0);
4679
4680     for ( i=0; i<pBRLRequestCB->Count; i++ ) {
4681         pResultCB->Result[i].LockType = pBRLRequestCB->Request[i].LockType;
4682         pResultCB->Result[i].Offset = pBRLRequestCB->Request[i].Offset;
4683         pResultCB->Result[i].Length = pBRLRequestCB->Request[i].Length;
4684
4685         code = cm_Lock(scp,
4686                        pBRLRequestCB->Request[i].LockType == AFS_BYTE_RANGE_LOCK_TYPE_SHARED,
4687                        pBRLRequestCB->Request[i].Offset,
4688                        pBRLRequestCB->Request[i].Length,
4689                        key, 0, userp, &req, NULL);
4690
4691         if (code) {
4692             osi_Log4(afsd_logp, "RDR_ByteRangeLockSync FAILURE code 0x%x type 0x%u offset 0x%x:%x",
4693                      code,
4694                      pBRLRequestCB->Request[i].LockType,
4695                      pBRLRequestCB->Request[i].Offset.HighPart,
4696                      pBRLRequestCB->Request[i].Offset.LowPart);
4697             osi_Log2(afsd_logp, "... length 0x%x:%x",
4698                      pBRLRequestCB->Request[i].Length.HighPart,
4699                      pBRLRequestCB->Request[i].Length.LowPart);
4700         }
4701
4702         switch (code) {
4703         case 0:
4704             pResultCB->Result[i].Status = 0;
4705             break;
4706         case CM_ERROR_WOULDBLOCK:
4707             pResultCB->Result[i].Status = STATUS_FILE_LOCK_CONFLICT;
4708             break;
4709         default:
4710             pResultCB->Result[i].Status = STATUS_LOCK_NOT_GRANTED;
4711         }
4712     }
4713
4714     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4715     lock_ReleaseWrite(&scp->rw);
4716     cm_ReleaseSCache(scp);
4717
4718     (*ResultCB)->ResultStatus = 0;
4719     osi_Log0(afsd_logp, "RDR_ByteRangeLockSync SUCCESS");
4720     return;
4721 }
4722
4723 void
4724 RDR_ByteRangeUnlock( IN cm_user_t     *userp,
4725                      IN AFSFileID     FileId,
4726                      IN AFSByteRangeUnlockRequestCB *pBRURequestCB,
4727                      IN BOOL bWow64,
4728                      IN DWORD ResultBufferLength,
4729                      IN OUT AFSCommResult **ResultCB)
4730 {
4731     AFSByteRangeUnlockResultCB *pResultCB = NULL;
4732     LARGE_INTEGER ProcessId;
4733     DWORD       Length;
4734     cm_scache_t *scp = NULL;
4735     cm_fid_t    Fid;
4736     afs_uint32  code;
4737     cm_req_t    req;
4738     cm_key_t    key;
4739     DWORD       i;
4740     DWORD       status;
4741
4742     ProcessId.QuadPart = pBRURequestCB->ProcessId;
4743
4744     RDR_InitReq(&req, bWow64);
4745
4746     osi_Log4(afsd_logp, "RDR_ByteRangeUnlock File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
4747               FileId.Cell, FileId.Volume,
4748               FileId.Vnode, FileId.Unique);
4749     osi_Log2(afsd_logp, "... ProcessId 0x%x:%x",
4750              ProcessId.HighPart, ProcessId.LowPart);
4751
4752     Length = sizeof( AFSByteRangeUnlockResultCB) + ((pBRURequestCB->Count - 1) * sizeof(AFSByteRangeLockResult));
4753     if (Length > ResultBufferLength) {
4754         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult));
4755         if (!(*ResultCB))
4756             return;
4757         memset( *ResultCB, 0, sizeof(AFSCommResult));
4758         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
4759         return;
4760     }
4761
4762     *ResultCB = (AFSCommResult *)malloc( Length + sizeof( AFSCommResult) );
4763     if (!(*ResultCB))
4764         return;
4765     memset( *ResultCB, '\0', Length + sizeof( AFSCommResult) );
4766     (*ResultCB)->ResultBufferLength = Length;
4767
4768     pResultCB = (AFSByteRangeUnlockResultCB *)(*ResultCB)->ResultData;
4769     pResultCB->Count = pBRURequestCB->Count;
4770
4771     /* Allocate the extents from the buffer package */
4772     Fid.cell = FileId.Cell;
4773     Fid.volume = FileId.Volume;
4774     Fid.vnode = FileId.Vnode;
4775     Fid.unique = FileId.Unique;
4776     Fid.hash = FileId.Hash;
4777
4778     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
4779     if (code) {
4780         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4781         (*ResultCB)->ResultStatus = status;
4782         (*ResultCB)->ResultBufferLength = 0;
4783         osi_Log2(afsd_logp, "RDR_ByteRangeUnlock cm_GetSCache FID failure code=0x%x status=0x%x",
4784                   code, status);
4785         return;
4786     }
4787
4788     lock_ObtainWrite(&scp->rw);
4789
4790     /* start by looking up the file's end */
4791     code = cm_SyncOp(scp, NULL, userp, &req, 0,
4792                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4793     if (code) {
4794         lock_ReleaseWrite(&scp->rw);
4795         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4796         (*ResultCB)->ResultStatus = status;
4797         (*ResultCB)->ResultBufferLength = 0;
4798         osi_Log3(afsd_logp, "RDR_ByteRangeUnlock cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
4799                  scp, code, status);
4800         return;
4801     }
4802
4803     /* the scp is now locked and current */
4804     key = cm_GenerateKey(CM_SESSION_IFS, ProcessId.QuadPart, 0);
4805
4806     for ( i=0; i<pBRURequestCB->Count; i++ ) {
4807         pResultCB->Result[i].LockType = pBRURequestCB->Request[i].LockType;
4808         pResultCB->Result[i].Offset = pBRURequestCB->Request[i].Offset;
4809         pResultCB->Result[i].Length = pBRURequestCB->Request[i].Length;
4810
4811         code = cm_Unlock(scp,
4812                          pBRURequestCB->Request[i].LockType == AFS_BYTE_RANGE_LOCK_TYPE_SHARED,
4813                          pBRURequestCB->Request[i].Offset,
4814                          pBRURequestCB->Request[i].Length,
4815                          key, CM_UNLOCK_FLAG_MATCH_RANGE, userp, &req);
4816
4817         if (code) {
4818             osi_Log4(afsd_logp, "RDR_ByteRangeUnlock FAILURE code 0x%x type 0x%u offset 0x%x:%x",
4819                      code, pBRURequestCB->Request[i].LockType,
4820                      pBRURequestCB->Request[i].Offset.HighPart,
4821                      pBRURequestCB->Request[i].Offset.LowPart);
4822             osi_Log2(afsd_logp, "... length 0x%x:%x",
4823                      pBRURequestCB->Request[i].Length.HighPart,
4824                      pBRURequestCB->Request[i].Length.LowPart);
4825         }
4826         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4827         pResultCB->Result[i].Status = status;
4828     }
4829
4830     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4831     lock_ReleaseWrite(&scp->rw);
4832     cm_ReleaseSCache(scp);
4833
4834     (*ResultCB)->ResultStatus = 0;
4835     osi_Log0(afsd_logp, "RDR_ByteRangeUnlock SUCCESS");
4836     return;
4837 }
4838
4839 void
4840 RDR_ByteRangeUnlockAll( IN cm_user_t     *userp,
4841                         IN AFSFileID     FileId,
4842                         IN AFSByteRangeUnlockRequestCB *pBRURequestCB,
4843                         IN BOOL bWow64,
4844                         IN DWORD ResultBufferLength,
4845                         IN OUT AFSCommResult **ResultCB)
4846 {
4847     AFSByteRangeUnlockResultCB *pResultCB = NULL;
4848     LARGE_INTEGER ProcessId;
4849     cm_scache_t *scp = NULL;
4850     cm_fid_t    Fid;
4851     afs_uint32  code;
4852     cm_req_t    req;
4853     cm_key_t    key;
4854     DWORD       status;
4855
4856     ProcessId.QuadPart = pBRURequestCB->ProcessId;
4857
4858     RDR_InitReq(&req, bWow64);
4859
4860     osi_Log4(afsd_logp, "RDR_ByteRangeUnlockAll File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
4861               FileId.Cell, FileId.Volume,
4862               FileId.Vnode, FileId.Unique);
4863     osi_Log2(afsd_logp, "... ProcessId 0x%x:%x",
4864              ProcessId.HighPart, ProcessId.LowPart);
4865
4866     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
4867     if (!(*ResultCB))
4868         return;
4869     memset( *ResultCB, '\0', sizeof( AFSCommResult));
4870     (*ResultCB)->ResultBufferLength = 0;
4871
4872     /* Allocate the extents from the buffer package */
4873     Fid.cell = FileId.Cell;
4874     Fid.volume = FileId.Volume;
4875     Fid.vnode = FileId.Vnode;
4876     Fid.unique = FileId.Unique;
4877     Fid.hash = FileId.Hash;
4878
4879     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
4880     if (code) {
4881         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4882         (*ResultCB)->ResultStatus = status;
4883         (*ResultCB)->ResultBufferLength = 0;
4884         osi_Log2(afsd_logp, "RDR_ByteRangeUnlockAll cm_GetSCache FID failure code=0x%x status=0x%x",
4885                   code, status);
4886         return;
4887     }
4888
4889     lock_ObtainWrite(&scp->rw);
4890
4891     /* start by looking up the file's end */
4892     code = cm_SyncOp(scp, NULL, userp, &req, 0,
4893                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4894     if (code) {
4895         lock_ReleaseWrite(&scp->rw);
4896         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4897         (*ResultCB)->ResultStatus = status;
4898         (*ResultCB)->ResultBufferLength = 0;
4899         osi_Log3(afsd_logp, "RDR_ByteRangeUnlockAll cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
4900                  scp, code, status);
4901         return;
4902     }
4903
4904     /* the scp is now locked and current */
4905     key = cm_GenerateKey(CM_SESSION_IFS, ProcessId.QuadPart, 0);
4906
4907     code = cm_UnlockByKey(scp, key, 0, userp, &req);
4908
4909     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4910     lock_ReleaseWrite(&scp->rw);
4911     cm_ReleaseSCache(scp);
4912
4913     smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4914     (*ResultCB)->ResultStatus = status;
4915
4916     if (code)
4917         osi_Log1(afsd_logp, "RDR_ByteRangeUnlockAll FAILURE code 0x%x", code);
4918     else
4919         osi_Log0(afsd_logp, "RDR_ByteRangeUnlockAll SUCCESS");
4920     return;
4921
4922 }
4923
4924 void
4925 RDR_GetVolumeInfo( IN cm_user_t     *userp,
4926                    IN AFSFileID     FileId,
4927                    IN BOOL bWow64,
4928                    IN DWORD ResultBufferLength,
4929                    IN OUT AFSCommResult **ResultCB)
4930 {
4931     AFSVolumeInfoCB *pResultCB = NULL;
4932     DWORD       Length;
4933     cm_scache_t *scp = NULL;
4934     cm_volume_t *volp = NULL;
4935     afs_uint32   volType;
4936     cm_cell_t   *cellp = NULL;
4937     cm_fid_t    Fid;
4938     afs_uint32  code;
4939     cm_req_t    req;
4940     DWORD       status;
4941     FILETIME ft = {0x832cf000, 0x01abfcc4}; /* October 1, 1982 00:00:00 +0600 */
4942
4943     char volName[32]="(unknown)";
4944     char offLineMsg[256]="server temporarily inaccessible";
4945     char motd[256]="server temporarily inaccessible";
4946     cm_conn_t *connp;
4947     AFSFetchVolumeStatus volStat;
4948     char *Name;
4949     char *OfflineMsg;
4950     char *MOTD;
4951     struct rx_connection * rxconnp;
4952     int sync_done = 0;
4953     int scp_locked = 0;
4954
4955     RDR_InitReq(&req, bWow64);
4956
4957     osi_Log4(afsd_logp, "RDR_GetVolumeInfo File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
4958              FileId.Cell, FileId.Volume,
4959              FileId.Vnode, FileId.Unique);
4960
4961     Length = sizeof( AFSCommResult) + sizeof(AFSVolumeInfoCB);
4962     if (sizeof(AFSVolumeInfoCB) > ResultBufferLength) {
4963         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult) );
4964         if (!(*ResultCB))
4965             return;
4966         memset( *ResultCB, 0, sizeof(AFSCommResult));
4967         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
4968         return;
4969     }
4970
4971     *ResultCB = (AFSCommResult *)malloc( Length );
4972     if (!(*ResultCB))
4973         return;
4974     memset( *ResultCB, '\0', Length );
4975     (*ResultCB)->ResultBufferLength = sizeof(AFSVolumeInfoCB);
4976     pResultCB = (AFSVolumeInfoCB *)(*ResultCB)->ResultData;
4977
4978     if (FileId.Cell != 0) {
4979         cm_SetFid(&Fid, FileId.Cell, FileId.Volume, 1, 1);
4980         code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
4981         if (code) {
4982             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4983             (*ResultCB)->ResultStatus = status;
4984             (*ResultCB)->ResultBufferLength = 0;
4985             osi_Log2(afsd_logp, "RDR_GetVolumeInfo cm_GetSCache FID failure code=0x%x status=0x%x",
4986                       code, status);
4987             return;
4988         }
4989     } else {
4990         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
4991         osi_Log0(afsd_logp, "RDR_GetVolumeInfo Object Name Invalid - Cell = 0");
4992         return;
4993     }
4994     lock_ObtainWrite(&scp->rw);
4995     scp_locked = 1;
4996
4997     pResultCB->SectorsPerAllocationUnit = 1;
4998     pResultCB->BytesPerSector = 1024;
4999
5000     pResultCB->CellID = scp->fid.cell;
5001     pResultCB->VolumeID = scp->fid.volume;
5002     pResultCB->Characteristics = FILE_REMOTE_DEVICE;
5003     pResultCB->FileSystemAttributes = FILE_CASE_PRESERVED_NAMES | FILE_UNICODE_ON_DISK |
5004         FILE_SUPPORTS_REPARSE_POINTS;
5005
5006     if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
5007          scp->fid.volume==AFS_FAKE_ROOT_VOL_ID)
5008     {
5009         pResultCB->TotalAllocationUnits.QuadPart = 100;
5010         memcpy(&pResultCB->VolumeCreationTime, &ft, sizeof(ft));
5011
5012         pResultCB->AvailableAllocationUnits.QuadPart = 0;
5013         pResultCB->Characteristics |= FILE_READ_ONLY_DEVICE;
5014
5015         pResultCB->VolumeLabelLength = cm_Utf8ToUtf16( "Freelance.Local.Root", -1, pResultCB->VolumeLabel,
5016                                                        (sizeof(pResultCB->VolumeLabel) / sizeof(WCHAR)) + 1);
5017         if ( pResultCB->VolumeLabelLength )
5018             pResultCB->VolumeLabelLength--;
5019     } else {
5020         memcpy(&pResultCB->VolumeCreationTime, &ft, sizeof(ft));
5021
5022         volp = cm_GetVolumeByFID(&scp->fid);
5023         if (!volp) {
5024             code = CM_ERROR_NOSUCHVOLUME;
5025             goto _done;
5026         }
5027         volType = cm_VolumeType(volp, scp->fid.volume);
5028
5029         pResultCB->Characteristics |= ((volType == ROVOL || volType == BACKVOL) ? FILE_READ_ONLY_DEVICE : 0);
5030
5031         code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_READ,
5032                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5033         if (code == 0)
5034         {
5035             sync_done = 1;
5036
5037             Name = volName;
5038             OfflineMsg = offLineMsg;
5039             MOTD = motd;
5040             lock_ReleaseWrite(&scp->rw);
5041             scp_locked = 0;
5042
5043             do {
5044                 code = cm_ConnFromFID(&scp->fid, userp, &req, &connp);
5045                 if (code) continue;
5046
5047                 rxconnp = cm_GetRxConn(connp);
5048                 code = RXAFS_GetVolumeStatus(rxconnp, scp->fid.volume,
5049                                               &volStat, &Name, &OfflineMsg, &MOTD);
5050                 rx_PutConnection(rxconnp);
5051
5052             } while (cm_Analyze(connp, userp, &req, &scp->fid, NULL, 0, NULL, NULL, NULL, code));
5053             code = cm_MapRPCError(code, &req);
5054         }
5055
5056         if (code == 0) {
5057             if (volStat.MaxQuota)
5058             {
5059                 pResultCB->TotalAllocationUnits.QuadPart = volStat.MaxQuota;
5060                 if (volType == ROVOL || volType == BACKVOL) {
5061                     pResultCB->AvailableAllocationUnits.QuadPart = 0;
5062                 }
5063                 else
5064                 {
5065                     pResultCB->AvailableAllocationUnits.QuadPart =
5066                         min(volStat.MaxQuota - volStat.BlocksInUse, volStat.PartBlocksAvail);
5067                 }
5068             }
5069             else
5070             {
5071                 pResultCB->TotalAllocationUnits.QuadPart = volStat.PartMaxBlocks;
5072                 if (volType == ROVOL || volType == BACKVOL) {
5073                     pResultCB->AvailableAllocationUnits.QuadPart = 0;
5074                 }
5075                 else
5076                 {
5077                     pResultCB->AvailableAllocationUnits.QuadPart = volStat.PartBlocksAvail;
5078                 }
5079             }
5080         } else {
5081             /*
5082              * Lie about the available space.  Out of quota errors will need
5083              * detected when the file server rejects the store data.
5084              */
5085             pResultCB->TotalAllocationUnits.QuadPart = 0x7FFFFFFF;
5086             pResultCB->AvailableAllocationUnits.QuadPart = (volType == ROVOL || volType == BACKVOL) ? 0 : 0x3F000000;
5087             code = 0;
5088         }
5089
5090         pResultCB->VolumeLabelLength = cm_Utf8ToUtf16( volp->namep, -1, pResultCB->VolumeLabel,
5091                                                        (sizeof(pResultCB->VolumeLabel) / sizeof(WCHAR)) + 1);
5092         if ( pResultCB->VolumeLabelLength )
5093             pResultCB->VolumeLabelLength--;
5094
5095         if (sync_done) {
5096             if (!scp_locked) {
5097                 lock_ObtainWrite(&scp->rw);
5098                 scp_locked = 1;
5099             }
5100             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5101         }
5102     }
5103     pResultCB->VolumeLabelLength *= sizeof(WCHAR);  /* convert to bytes from chars */
5104
5105   _done:
5106     if (scp_locked)
5107         lock_ReleaseWrite(&scp->rw);
5108     if (volp)
5109        cm_PutVolume(volp);
5110     cm_ReleaseSCache(scp);
5111
5112     smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5113     (*ResultCB)->ResultStatus = status;
5114     osi_Log0(afsd_logp, "RDR_GetVolumeInfo SUCCESS");
5115     return;
5116 }
5117
5118 void
5119 RDR_GetVolumeSizeInfo( IN cm_user_t     *userp,
5120                    IN AFSFileID     FileId,
5121                    IN BOOL bWow64,
5122                    IN DWORD ResultBufferLength,
5123                    IN OUT AFSCommResult **ResultCB)
5124 {
5125     AFSVolumeSizeInfoCB *pResultCB = NULL;
5126     DWORD       Length;
5127     cm_scache_t *scp = NULL;
5128     cm_volume_t *volp = NULL;
5129     afs_uint32   volType;
5130     cm_cell_t   *cellp = NULL;
5131     cm_fid_t    Fid;
5132     afs_uint32  code;
5133     cm_req_t    req;
5134     DWORD       status;
5135
5136     char volName[32]="(unknown)";
5137     char offLineMsg[256]="server temporarily inaccessible";
5138     char motd[256]="server temporarily inaccessible";
5139     cm_conn_t *connp;
5140     AFSFetchVolumeStatus volStat;
5141     char *Name;
5142     char *OfflineMsg;
5143     char *MOTD;
5144     struct rx_connection * rxconnp;
5145     int sync_done = 0;
5146     int scp_locked = 0;
5147
5148     RDR_InitReq(&req, bWow64);
5149
5150     osi_Log4(afsd_logp, "RDR_GetVolumeSizeInfo File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
5151              FileId.Cell, FileId.Volume,
5152              FileId.Vnode, FileId.Unique);
5153
5154     Length = sizeof( AFSCommResult) + sizeof(AFSVolumeSizeInfoCB);
5155     if (sizeof(AFSVolumeSizeInfoCB) > ResultBufferLength) {
5156         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult) );
5157         if (!(*ResultCB))
5158             return;
5159         memset( *ResultCB, 0, sizeof(AFSCommResult));
5160         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
5161         return;
5162     }
5163
5164     *ResultCB = (AFSCommResult *)malloc( Length );
5165     if (!(*ResultCB))
5166         return;
5167     memset( *ResultCB, '\0', Length );
5168     (*ResultCB)->ResultBufferLength = sizeof(AFSVolumeSizeInfoCB);
5169     pResultCB = (AFSVolumeSizeInfoCB *)(*ResultCB)->ResultData;
5170
5171     if (FileId.Cell != 0) {
5172         cm_SetFid(&Fid, FileId.Cell, FileId.Volume, 1, 1);
5173         code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
5174         if (code) {
5175             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5176             (*ResultCB)->ResultStatus = status;
5177             (*ResultCB)->ResultBufferLength = 0;
5178             osi_Log2(afsd_logp, "RDR_GetVolumeSizeInfo cm_GetSCache FID failure code=0x%x status=0x%x",
5179                       code, status);
5180             return;
5181         }
5182     } else {
5183         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
5184         osi_Log0(afsd_logp, "RDR_GetVolumeSizeInfo Object Name Invalid - Cell = 0");
5185         return;
5186     }
5187     lock_ObtainWrite(&scp->rw);
5188     scp_locked = 1;
5189
5190     pResultCB->SectorsPerAllocationUnit = 1;
5191     pResultCB->BytesPerSector = 1024;
5192
5193     if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
5194         scp->fid.volume==AFS_FAKE_ROOT_VOL_ID)
5195     {
5196         pResultCB->TotalAllocationUnits.QuadPart = 100;
5197         pResultCB->AvailableAllocationUnits.QuadPart = 0;
5198     } else {
5199         volp = cm_GetVolumeByFID(&scp->fid);
5200         if (!volp) {
5201             code = CM_ERROR_NOSUCHVOLUME;
5202             goto _done;
5203         }
5204
5205         volType = cm_VolumeType(volp, scp->fid.volume);
5206
5207         code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_READ,
5208                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5209         if (code == 0)
5210         {
5211             sync_done = 1;
5212
5213             Name = volName;
5214             OfflineMsg = offLineMsg;
5215             MOTD = motd;
5216             lock_ReleaseWrite(&scp->rw);
5217             scp_locked = 0;
5218
5219             do {
5220                 code = cm_ConnFromFID(&scp->fid, userp, &req, &connp);
5221                 if (code) continue;
5222
5223                 rxconnp = cm_GetRxConn(connp);
5224                 code = RXAFS_GetVolumeStatus(rxconnp, scp->fid.volume,
5225                                               &volStat, &Name, &OfflineMsg, &MOTD);
5226                 rx_PutConnection(rxconnp);
5227
5228             } while (cm_Analyze(connp, userp, &req, &scp->fid, NULL, 0, NULL, NULL, NULL, code));
5229             code = cm_MapRPCError(code, &req);
5230         }
5231
5232         if (code == 0) {
5233             if (volStat.MaxQuota)
5234             {
5235                 pResultCB->TotalAllocationUnits.QuadPart = volStat.MaxQuota;
5236                 if (volType == ROVOL || volType == BACKVOL) {
5237                     pResultCB->AvailableAllocationUnits.QuadPart = 0;
5238                 }
5239                 else
5240                 {
5241                     pResultCB->AvailableAllocationUnits.QuadPart =
5242                         min(volStat.MaxQuota - volStat.BlocksInUse, volStat.PartBlocksAvail);
5243                 }
5244             }
5245             else
5246             {
5247                 pResultCB->TotalAllocationUnits.QuadPart = volStat.PartMaxBlocks;
5248                 if (volType == ROVOL || volType == BACKVOL) {
5249                     pResultCB->AvailableAllocationUnits.QuadPart = 0;
5250                 }
5251                 else
5252                 {
5253                     pResultCB->AvailableAllocationUnits.QuadPart = volStat.PartBlocksAvail;
5254                 }
5255             }
5256         } else {
5257             /*
5258              * Lie about the available space.  Out of quota errors will need
5259              * detected when the file server rejects the store data.
5260              */
5261             pResultCB->TotalAllocationUnits.QuadPart = 0x7FFFFFFF;
5262             pResultCB->AvailableAllocationUnits.QuadPart = (volType == ROVOL || volType == BACKVOL) ? 0 : 0x3F000000;
5263             code = 0;
5264         }
5265
5266         if (sync_done) {
5267             if (!scp_locked) {
5268                 lock_ObtainWrite(&scp->rw);
5269                 scp_locked = 1;
5270             }
5271             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5272         }
5273     }
5274
5275   _done:
5276     if (scp_locked)
5277         lock_ReleaseWrite(&scp->rw);
5278     if (volp)
5279        cm_PutVolume(volp);
5280     cm_ReleaseSCache(scp);
5281
5282     smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5283     (*ResultCB)->ResultStatus = status;
5284     osi_Log0(afsd_logp, "RDR_GetVolumeSizeInfo SUCCESS");
5285     return;
5286 }
5287
5288 void
5289 RDR_HoldFid( IN cm_user_t     *userp,
5290              IN AFSHoldFidRequestCB * pHoldFidCB,
5291              IN BOOL bFast,
5292              IN DWORD ResultBufferLength,
5293              IN OUT AFSCommResult **ResultCB)
5294 {
5295     AFSHoldFidResultCB *pResultCB = NULL;
5296     DWORD       index;
5297     DWORD       Length;
5298     cm_req_t    req;
5299
5300     RDR_InitReq(&req, FALSE);
5301
5302     osi_Log1(afsd_logp, "RDR_HoldFid Count=%u", pHoldFidCB->Count);
5303
5304     Length = sizeof(AFSHoldFidResultCB) + (pHoldFidCB->Count-1) * sizeof(AFSFidResult);
5305     if (Length > ResultBufferLength) {
5306         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult) );
5307         if (!(*ResultCB))
5308             return;
5309         memset( *ResultCB, 0, sizeof(AFSCommResult));
5310         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
5311         return;
5312     }
5313     *ResultCB = (AFSCommResult *)malloc( Length + sizeof( AFSCommResult) );
5314     if (!(*ResultCB))
5315         return;
5316     memset( *ResultCB, '\0', Length );
5317     (*ResultCB)->ResultBufferLength = Length;
5318     pResultCB = (AFSHoldFidResultCB *)(*ResultCB)->ResultData;
5319
5320     for ( index = 0; index < pHoldFidCB->Count; index++ )
5321     {
5322         cm_scache_t *scp = NULL;
5323         cm_fid_t    Fid;
5324
5325         Fid.cell   = pResultCB->Result[index].FileID.Cell   = pHoldFidCB->FileID[index].Cell;
5326         Fid.volume = pResultCB->Result[index].FileID.Volume = pHoldFidCB->FileID[index].Volume;
5327         Fid.vnode  = pResultCB->Result[index].FileID.Vnode  = pHoldFidCB->FileID[index].Vnode;
5328         Fid.unique = pResultCB->Result[index].FileID.Unique = pHoldFidCB->FileID[index].Unique;
5329         Fid.hash   = pResultCB->Result[index].FileID.Hash   = pHoldFidCB->FileID[index].Hash;
5330
5331         osi_Log4( afsd_logp,
5332                   "RDR_HoldFid File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
5333                   Fid.cell, Fid.volume, Fid.vnode, Fid.unique);
5334
5335         scp = cm_FindSCache(&Fid);
5336         if (scp) {
5337             RDR_FlagScpInUse( scp, FALSE );
5338             cm_ReleaseSCache(scp);
5339         }
5340         pResultCB->Result[index].Status = 0;
5341     }
5342
5343     (*ResultCB)->ResultStatus = 0;
5344     osi_Log0(afsd_logp, "RDR_HoldFid SUCCESS");
5345     return;
5346 }
5347
5348 void
5349 RDR_ReleaseFid( IN cm_user_t     *userp,
5350                 IN AFSReleaseFidRequestCB * pReleaseFidCB,
5351                 IN BOOL bFast,
5352                 IN DWORD ResultBufferLength,
5353                 IN OUT AFSCommResult **ResultCB)
5354 {
5355     AFSReleaseFidResultCB *pResultCB = NULL;
5356     DWORD       index;
5357     DWORD       Length;
5358     cm_req_t    req;
5359
5360     RDR_InitReq(&req, FALSE);
5361
5362     osi_Log1(afsd_logp, "RDR_ReleaseFid Count=%u", pReleaseFidCB->Count);
5363
5364     Length = sizeof(AFSReleaseFidResultCB) + (pReleaseFidCB->Count ? pReleaseFidCB->Count-1 : 0) * sizeof(AFSFidResult);
5365     if (Length > ResultBufferLength) {
5366         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult) );
5367         if (!(*ResultCB))
5368             return;
5369         memset( *ResultCB, 0, sizeof(AFSCommResult));
5370         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
5371         return;
5372     }
5373     *ResultCB = (AFSCommResult *)malloc( Length + sizeof( AFSCommResult) );
5374     if (!(*ResultCB))
5375         return;
5376     memset( *ResultCB, '\0', Length );
5377     (*ResultCB)->ResultBufferLength = Length;
5378     pResultCB = (AFSReleaseFidResultCB *)(*ResultCB)->ResultData;
5379
5380     for ( index = 0; index < pReleaseFidCB->Count; index++ )
5381     {
5382         cm_scache_t *scp = NULL;
5383         cm_fid_t    Fid;
5384
5385         Fid.cell   = pResultCB->Result[index].FileID.Cell   = pReleaseFidCB->FileID[index].Cell;
5386         Fid.volume = pResultCB->Result[index].FileID.Volume = pReleaseFidCB->FileID[index].Volume;
5387         Fid.vnode  = pResultCB->Result[index].FileID.Vnode  = pReleaseFidCB->FileID[index].Vnode;
5388         Fid.unique = pResultCB->Result[index].FileID.Unique = pReleaseFidCB->FileID[index].Unique;
5389         Fid.hash   = pResultCB->Result[index].FileID.Hash   = pReleaseFidCB->FileID[index].Hash;
5390
5391         osi_Log4( afsd_logp,
5392                   "RDR_ReleaseFid File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
5393                   Fid.cell, Fid.volume, Fid.vnode, Fid.unique);
5394
5395         scp = cm_FindSCache(&Fid);
5396         if (scp) {
5397             lock_ObtainWrite(&scp->rw);
5398             scp->flags &= ~CM_SCACHEFLAG_RDR_IN_USE;
5399             lock_ReleaseWrite(&scp->rw);
5400
5401             cm_ReleaseSCache(scp);
5402         }
5403         pResultCB->Result[index].Status = 0;
5404     }
5405     pResultCB->Count = pReleaseFidCB->Count;
5406
5407     (*ResultCB)->ResultStatus = 0;
5408     osi_Log0(afsd_logp, "RDR_ReleaseFid SUCCESS");
5409     return;
5410 }
5411
5412 /*
5413  * The redirector makes several assumptions regarding the
5414  * SRVSVC and WKSSVC pipes transactions.  First, the interface
5415  * versions are those indicated below.  Secondly, the encoding
5416  * will be performed using NDR version 2.  These assumptions
5417  * may not hold in the future and end-to-end MSRPC Bind
5418  * negotiations may need to be supported.  Of course, these
5419  * are the only interface versions that are supported by the
5420  * service.
5421  */
5422 #define MSRPC_PIPE_PREFIX L".\\"
5423
5424 static const UUID MSRPC_SRVSVC_UUID = {0x4B324FC8, 0x1670, 0x01D3,
5425                                        {0x12, 0x78, 0x5A, 0x47, 0xBF, 0x6E, 0xE1, 0x88}};
5426 #define MSRPC_SRVSVC_NAME L"PIPE\\SRVSVC"
5427 #define MSRPC_SRVSVC_VERS 3
5428
5429 static const UUID MSRPC_WKSSVC_UUID = {0x6BFFD098, 0xA112, 0x3610,
5430                                        {0x98, 0x33, 0x46, 0xC3, 0xF8, 0x7E, 0x34, 0x5A}};
5431 #define MSRPC_WKSSVC_NAME L"PIPE\\WKSSVC"
5432 #define MSRPC_WKSSVC_VERS 1
5433
5434 static const UUID MSRPC_NDR_UUID = {0x8A885D04, 0x1CEB, 0x11C9,
5435                                     {0x9F, 0xE8, 0x08, 0x00, 0x2B, 0x10, 0x48, 0x60}};
5436 #define MSRPC_NDR_NAME    L"NDR"
5437 #define MSRPC_NDR_VERS    2
5438
5439 extern RPC_IF_HANDLE srvsvc_v3_0_s_ifspec;
5440 extern RPC_IF_HANDLE wkssvc_v1_0_s_ifspec;
5441
5442 void
5443 RDR_PipeOpen( IN cm_user_t *userp,
5444               IN AFSFileID  ParentId,
5445               IN WCHAR     *Name,
5446               IN DWORD      NameLength,
5447               IN AFSPipeOpenCloseRequestCB *pPipe_CB,
5448               IN BOOL bWow64,
5449               IN DWORD ResultBufferLength,
5450               IN OUT AFSCommResult **ResultCB)
5451 {
5452     cm_fid_t    ParentFid;
5453     cm_fid_t    RootFid;
5454
5455     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
5456     if (!(*ResultCB))
5457         return;
5458
5459     memset( *ResultCB,
5460             '\0',
5461             sizeof( AFSCommResult));
5462
5463     /* Get the active directory */
5464     ParentFid.cell = ParentId.Cell;
5465     ParentFid.volume = ParentId.Volume;
5466     ParentFid.vnode = ParentId.Vnode;
5467     ParentFid.unique = ParentId.Unique;
5468     ParentFid.hash = ParentId.Hash;
5469
5470     /* Get the root directory */
5471     RootFid.cell = pPipe_CB->RootId.Cell;
5472     RootFid.volume = pPipe_CB->RootId.Volume;
5473     RootFid.vnode = pPipe_CB->RootId.Vnode;
5474     RootFid.unique = pPipe_CB->RootId.Unique;
5475     RootFid.hash = pPipe_CB->RootId.Hash;
5476
5477     /* Create the pipe index */
5478     (*ResultCB)->ResultStatus =
5479       RDR_SetupPipe( pPipe_CB->RequestId, &ParentFid, &RootFid,
5480                      Name, NameLength, userp);
5481     return;
5482 }
5483
5484
5485 void
5486 RDR_PipeClose( IN cm_user_t *userp,
5487                IN AFSFileID  ParentId,
5488                IN AFSPipeOpenCloseRequestCB *pPipe_CB,
5489                IN BOOL bWow64,
5490                IN DWORD ResultBufferLength,
5491                IN OUT AFSCommResult **ResultCB)
5492 {
5493     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
5494     if (!(*ResultCB))
5495         return;
5496
5497     memset( *ResultCB,
5498             '\0',
5499             sizeof( AFSCommResult));
5500
5501     /* Cleanup the pipe index */
5502     RDR_CleanupPipe(pPipe_CB->RequestId);
5503
5504     return;
5505 }
5506
5507
5508 void
5509 RDR_PipeWrite( IN cm_user_t *userp,
5510                IN AFSFileID  ParentId,
5511                IN AFSPipeIORequestCB *pPipe_CB,
5512                IN BYTE *pPipe_Data,
5513                IN BOOL bWow64,
5514                IN DWORD ResultBufferLength,
5515                IN OUT AFSCommResult **ResultCB)
5516 {
5517     AFSPipeIOResultCB *pResultCB;
5518     cm_scache_t *dscp = NULL;
5519     afs_uint32  code;
5520     cm_req_t    req;
5521     DWORD       status;
5522
5523     RDR_InitReq(&req, bWow64);
5524
5525     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof(AFSPipeIOResultCB));
5526     if (!(*ResultCB))
5527         return;
5528
5529     memset( *ResultCB,
5530             '\0',
5531             sizeof( AFSCommResult) + sizeof(AFSPipeIOResultCB));
5532
5533     pResultCB = (AFSPipeIOResultCB *)(*ResultCB)->ResultData;
5534
5535     code = RDR_Pipe_Write( pPipe_CB->RequestId, pPipe_CB->BufferLength, pPipe_Data, &req, userp);
5536     if (code) {
5537         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5538         (*ResultCB)->ResultStatus = status;
5539         return;
5540     }
5541
5542     pResultCB->BytesProcessed = pPipe_CB->BufferLength;
5543     (*ResultCB)->ResultBufferLength = sizeof( AFSPipeIOResultCB);
5544 }
5545
5546
5547 void
5548 RDR_PipeRead( IN cm_user_t *userp,
5549               IN AFSFileID  ParentId,
5550               IN AFSPipeIORequestCB *pPipe_CB,
5551               IN BOOL bWow64,
5552               IN DWORD ResultBufferLength,
5553               IN OUT AFSCommResult **ResultCB)
5554 {
5555     BYTE *pPipe_Data;
5556     cm_scache_t *dscp = NULL;
5557     afs_uint32  code;
5558     cm_req_t    req;
5559     DWORD       status;
5560
5561     RDR_InitReq(&req, bWow64);
5562
5563     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + ResultBufferLength);
5564     if (!(*ResultCB))
5565         return;
5566
5567     memset( *ResultCB,
5568             '\0',
5569             sizeof( AFSCommResult));
5570
5571     pPipe_Data = (BYTE *)(*ResultCB)->ResultData;
5572
5573     code = RDR_Pipe_Read( pPipe_CB->RequestId, ResultBufferLength, pPipe_Data,
5574                           &(*ResultCB)->ResultBufferLength, &req, userp);
5575     if (code) {
5576         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5577         (*ResultCB)->ResultStatus = status;
5578         return;
5579     }
5580 }
5581
5582
5583 void
5584 RDR_PipeSetInfo( IN cm_user_t *userp,
5585                  IN AFSFileID  ParentId,
5586                  IN AFSPipeInfoRequestCB *pPipeInfo_CB,
5587                  IN BYTE *pPipe_Data,
5588                  IN BOOL bWow64,
5589                  IN DWORD ResultBufferLength,
5590                  IN OUT AFSCommResult **ResultCB)
5591 {
5592     cm_scache_t *dscp = NULL;
5593     cm_req_t    req;
5594     DWORD       status;
5595
5596     RDR_InitReq(&req, bWow64);
5597
5598     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
5599     if (!(*ResultCB))
5600         return;
5601
5602     memset( *ResultCB,
5603             '\0',
5604             sizeof( AFSCommResult));
5605
5606     status = RDR_Pipe_SetInfo( pPipeInfo_CB->RequestId, pPipeInfo_CB->InformationClass,
5607                                pPipeInfo_CB->BufferLength, pPipe_Data, &req, userp);
5608
5609     (*ResultCB)->ResultStatus = status;
5610 }
5611
5612
5613 void
5614 RDR_PipeQueryInfo( IN cm_user_t *userp,
5615                    IN AFSFileID  ParentId,
5616                    IN AFSPipeInfoRequestCB *pPipeInfo_CB,
5617                    IN BOOL bWow64,
5618                    IN DWORD ResultBufferLength,
5619                    IN OUT AFSCommResult **ResultCB)
5620 {
5621     BYTE *pPipe_Data;
5622     cm_scache_t *dscp = NULL;
5623     cm_req_t    req;
5624     DWORD       status;
5625
5626     RDR_InitReq(&req, bWow64);
5627
5628     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + ResultBufferLength);
5629     if (!(*ResultCB))
5630         return;
5631
5632     memset( *ResultCB,
5633             '\0',
5634             sizeof( AFSCommResult) + sizeof(AFSPipeIOResultCB));
5635
5636     pPipe_Data = (BYTE *)(*ResultCB)->ResultData;
5637
5638     status = RDR_Pipe_QueryInfo( pPipeInfo_CB->RequestId, pPipeInfo_CB->InformationClass,
5639                                  ResultBufferLength, pPipe_Data,
5640                                  &(*ResultCB)->ResultBufferLength, &req, userp);
5641
5642     (*ResultCB)->ResultStatus = status;
5643 }
5644
5645 void
5646 RDR_PipeTransceive( IN cm_user_t     *userp,
5647                     IN AFSFileID  ParentId,
5648                     IN AFSPipeIORequestCB *pPipe_CB,
5649                     IN BYTE *pPipe_InData,
5650                     IN BOOL bWow64,
5651                     IN DWORD ResultBufferLength,
5652                     IN OUT AFSCommResult **ResultCB)
5653 {
5654     /*
5655      * This function processes a Pipe Service request
5656      * that would normally be sent to a LAN Manager server
5657      * across an authenticated SMB-PIPE/MSRPC/SVC request
5658      * stack.  The request is being sent here because the
5659      * application (e.g., Explorer Shell or Common Control File
5660      * dialog) believes that because the UNC path it is
5661      * processing has specified a server name that is not
5662      * "." and that the Server is remote and that the Share
5663      * list cannot be obtained using the Network Provider
5664      * interface.
5665      *
5666      * The file system driver is faking the Bind-Ack response
5667      * to the MSRPC Bind request but cannot decode the NDR
5668      * encoded Pipe Service requests.  For that we will use
5669      * the service's MSRPC module.  However, unlike the SMB
5670      * server usage we must fake the MSRPC Bind exchange and
5671      * map the PipeName to an interface instead of using the
5672      * GUID specified in the MSRPC Bind request.
5673      *
5674      * None of the requests that are being processed by the
5675      * service require authentication.  As a result the userp
5676      * parameter will be ignored.
5677      *
5678      * Although there are dozens of Pipe Services, the only
5679      * ones that we are implementing are WKSSVC and SRVSVC.
5680      * These support NetShareEnum, NetShareGetInfo,
5681      * NetServerGetInfo, and NetWorkstaGetInfo which are
5682      * commonly queried by NET VIEW, the Explorer Shell,
5683      * and the Common Control File dialog.
5684      */
5685     BYTE *pPipe_OutData;
5686     cm_scache_t *dscp = NULL;
5687     afs_uint32  code;
5688     cm_req_t    req;
5689     DWORD       status;
5690     DWORD Length = ResultBufferLength + sizeof( AFSCommResult);
5691
5692     RDR_InitReq(&req, bWow64);
5693
5694     *ResultCB = (AFSCommResult *)malloc( Length);
5695     if (!(*ResultCB))
5696         return;
5697     memset( *ResultCB, '\0', Length );
5698
5699     code = RDR_Pipe_Write( pPipe_CB->RequestId, pPipe_CB->BufferLength, pPipe_InData, &req, userp);
5700     if (code) {
5701         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5702         osi_Log2( afsd_logp, "RDR_Pipe_Transceive Write FAILURE code=0x%x status=0x%x",
5703                   code, status);
5704         (*ResultCB)->ResultStatus = status;
5705         return;
5706     }
5707
5708     pPipe_OutData = (BYTE *)(*ResultCB)->ResultData;
5709     code = RDR_Pipe_Read( pPipe_CB->RequestId, ResultBufferLength, pPipe_OutData,
5710                           &(*ResultCB)->ResultBufferLength, &req, userp);
5711     if (code) {
5712         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5713         osi_Log2( afsd_logp, "RDR_Pipe_Transceive Read FAILURE code=0x%x status=0x%x",
5714                   code, status);
5715         (*ResultCB)->ResultStatus = status;
5716         return;
5717     }
5718
5719     (*ResultCB)->ResultStatus = 0;
5720     osi_Log0(afsd_logp, "RDR_Pipe_Transceive SUCCESS");
5721 }