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