b19bf047399311714d539c629ee84e5907054fcd
[openafs.git] / src / WINNT / afsd / afsd_init.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afs/param.h>
11 #include <afs/stds.h>
12 #include <afs/afs_args.h>
13
14 #include <windows.h>
15 #include <string.h>
16 #include <nb30.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <locale.h>
20 #include <mbctype.h>
21 #include <winsock2.h>
22 #include <ErrorRep.h>
23
24 #include <osi.h>
25 #include "afsd.h"
26 #ifdef USE_BPLUS
27 #include "cm_btree.h"
28 #endif
29 #include <rx\rx.h>
30 #include <rx\rx_null.h>
31 #include <rx\rxstat.h>
32 #include <WINNT/syscfg.h>
33 #include <WINNT/afsreg.h>
34 #include <afs\afscbint.h>
35
36 #include "smb.h"
37 #include "cm_rpc.h"
38 #include "lanahelper.h"
39 #include <strsafe.h>
40 #include "cm_memmap.h"
41 #include "msrpc.h"
42 #ifdef DEBUG
43 #include <crtdbg.h>
44 #endif
45
46 extern afs_uint32 cryptall;
47 extern afs_uint32 cm_anonvldb;
48 extern int cm_enableServerLocks;
49 extern int cm_followBackupPath;
50 extern int cm_deleteReadOnly;
51 #ifdef USE_BPLUS
52 extern afs_int32 cm_BPlusTrees;
53 #endif
54 extern afs_int32 cm_OfflineROIsValid;
55 extern afs_int32 cm_giveUpAllCBs;
56 extern const clientchar_t **smb_ExecutableExtensions;
57
58 osi_log_t *afsd_logp;
59
60 cm_config_data_t        cm_data;
61
62 fschar_t cm_rootVolumeName[VL_MAXNAMELEN];
63 DWORD cm_rootVolumeNameLen;
64
65 fschar_t cm_mountRoot[1024];
66 DWORD cm_mountRootLen;
67
68 clientchar_t cm_mountRootC[1024];
69 DWORD cm_mountRootCLen;
70
71 int cm_readonlyVolumeVersioning = 0;
72 int cm_logChunkSize;
73 int cm_chunkSize;
74
75 int smb_UseV3 = 1;
76
77 int LANadapter;
78
79 int numBkgD;
80 int numSvThreads;
81 long rx_mtu = -1;
82 int traceOnPanic = 0;
83
84 int logReady = 0;
85
86 char cm_HostName[200];
87 long cm_HostAddr;
88 unsigned short cm_callbackport = CM_DEFAULT_CALLBACKPORT;
89
90 char cm_NetbiosName[MAX_NB_NAME_LENGTH] = "NOT.YET.SET";
91 clientchar_t cm_NetbiosNameC[MAX_NB_NAME_LENGTH] = _C("NOT.YET.SET");
92
93 char cm_CachePath[MAX_PATH];
94 DWORD cm_ValidateCache = 1;
95
96 BOOL reportSessionStartups = FALSE;
97
98 cm_initparams_v1 cm_initParams;
99
100 clientchar_t *cm_sysName = 0;
101 unsigned int  cm_sysNameCount = 0;
102 clientchar_t *cm_sysNameList[MAXNUMSYSNAMES];
103
104 DWORD TraceOption = 0;
105
106 /*
107  * AFSD Initialization Log
108  *
109  * This is distinct from the regular debug logging facility.
110  * Log items go directly to a file, not to an array in memory, so that even
111  * if AFSD crashes, the log can be inspected.
112  */
113
114 HANDLE afsi_file;
115
116 int cm_dnsEnabled = 1;
117
118
119 static int afsi_log_useTimestamp = 1;
120
121 void
122 afsi_log(char *pattern, ...)
123 {
124     char s[256], t[100], d[100], u[512];
125     DWORD zilch;
126     va_list ap;
127     va_start(ap, pattern);
128
129     StringCbVPrintfA(s, sizeof(s), pattern, ap);
130     if ( afsi_log_useTimestamp ) {
131         GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
132         GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
133         StringCbPrintfA(u, sizeof(u), "%s %s: %s\r\n", d, t, s);
134         if (afsi_file != INVALID_HANDLE_VALUE)
135             WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
136 #ifdef NOTSERVICE
137         printf("%s", u);
138 #endif 
139     } else {
140         if (afsi_file != INVALID_HANDLE_VALUE)
141             WriteFile(afsi_file, s, (DWORD)strlen(s), &zilch, NULL);
142     }
143 }
144
145 void
146 afsi_start()
147 {
148     char wd[MAX_PATH+1];
149     char t[100], u[100], *p, *path;
150     int zilch;
151     DWORD code;
152     DWORD dwLow, dwHigh;
153     HKEY parmKey;
154     DWORD dummyLen;
155     DWORD maxLogSize = 100 * 1024;
156
157     afsi_file = INVALID_HANDLE_VALUE;
158     code = GetTempPath(sizeof(wd)-15, wd);
159     if ( code == 0 || code > (sizeof(wd)-15) )
160         return;         /* unable to create a log */
161
162     StringCbCatA(wd, sizeof(wd), "\\afsd_init.log");
163     GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
164     afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
165                            OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
166
167     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
168                          0, KEY_QUERY_VALUE, &parmKey);
169     if (code == ERROR_SUCCESS) {
170         dummyLen = sizeof(maxLogSize);
171         code = RegQueryValueEx(parmKey, "MaxLogSize", NULL, NULL,
172                                 (BYTE *) &maxLogSize, &dummyLen);
173         RegCloseKey (parmKey);
174     }
175
176     if (maxLogSize) {
177         dwLow = GetFileSize( afsi_file, &dwHigh );
178         if ( dwHigh > 0 || dwLow >= maxLogSize ) {
179             CloseHandle(afsi_file);
180             afsi_file = CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
181                                     CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
182         }
183     }
184
185     SetFilePointer(afsi_file, 0, NULL, FILE_END);
186     GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
187     StringCbCatA(t, sizeof(t), ": Create log file\r\n");
188     StringCbCatA(u, sizeof(u), ": Created log file\r\n");
189     WriteFile(afsi_file, t, (DWORD)strlen(t), &zilch, NULL);
190     WriteFile(afsi_file, u, (DWORD)strlen(u), &zilch, NULL);
191     p = "PATH=";
192     code = GetEnvironmentVariable("PATH", NULL, 0);
193     path = malloc(code);
194     code = GetEnvironmentVariable("PATH", path, code);
195     WriteFile(afsi_file, p, (DWORD)strlen(p), &zilch, NULL);
196     WriteFile(afsi_file, path, (DWORD)strlen(path), &zilch, NULL);
197     WriteFile(afsi_file, "\r\n", (DWORD)1, &zilch, NULL);
198     free(path);
199
200     /* Initialize C RTL Code Page conversion functions */
201     /* All of the path info obtained from the SMB client is in the OEM code page */
202     afsi_log("OEM Code Page = %d", GetOEMCP());
203     afsi_log("locale =  %s", setlocale(LC_ALL,NULL));
204 #ifdef COMMENT
205     /* Two things to look into.  First, should mbstowcs() be performing 
206      * character set translations from OEM to Unicode in smb3.c; 
207      * Second, do we need to set this translation in each function 
208      * due to multi-threading. 
209      */
210     afsi_log("locale -> %s", setlocale(LC_ALL, ".OCP"));
211     afsi_log("_setmbcp = %d -> %d", _setmbcp(_MB_CP_OEM), _getmbcp());
212 #endif /* COMMENT */
213 }
214
215 /*
216  * Standard AFSD trace
217  */
218
219 void afsd_ForceTrace(BOOL flush)
220 {
221     HANDLE handle;
222     int len;
223     char buf[256];
224
225     if (!logReady) 
226         return;
227
228     len = GetTempPath(sizeof(buf)-10, buf);
229     StringCbCopyA(&buf[len], sizeof(buf)-len, "/afsd.log");
230     handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
231                          NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
232     if (handle == INVALID_HANDLE_VALUE) {
233         logReady = 0;
234         osi_panic("Cannot create log file", __FILE__, __LINE__);
235     }
236     osi_LogPrint(afsd_logp, handle);
237     if (flush)
238         FlushFileBuffers(handle);
239     CloseHandle(handle);
240 }
241
242 static void afsd_InitServerPreferences(void)
243 {
244     HKEY hkPrefs = 0;
245     DWORD dwType, dwSize;
246     DWORD dwPrefs = 0;
247     DWORD dwIndex;
248     TCHAR szHost[256];
249     DWORD dwHostSize = 256;
250     DWORD dwRank;
251     struct sockaddr_in  saddr;
252     cm_server_t       *tsp;
253
254     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
255                       AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\VLDB",
256                       0,
257                       KEY_READ|KEY_QUERY_VALUE,
258                       &hkPrefs) == ERROR_SUCCESS) {
259
260         RegQueryInfoKey( hkPrefs,
261                          NULL,  /* lpClass */
262                          NULL,  /* lpcClass */
263                          NULL,  /* lpReserved */
264                          NULL,  /* lpcSubKeys */
265                          NULL,  /* lpcMaxSubKeyLen */
266                          NULL,  /* lpcMaxClassLen */
267                          &dwPrefs, /* lpcValues */
268                          NULL,  /* lpcMaxValueNameLen */
269                          NULL,  /* lpcMaxValueLen */
270                          NULL,  /* lpcbSecurityDescriptor */
271                          NULL   /* lpftLastWriteTime */
272                          );
273
274         for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
275
276             dwSize = sizeof(DWORD);
277             dwHostSize = 256;
278
279             if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
280                               &dwType, (LPBYTE)&dwRank, &dwSize))
281             {
282                 afsi_log("RegEnumValue(hkPrefs) failed");
283                 continue;
284             }
285
286             afsi_log("VLDB Server Preference: %s = %d",szHost, dwRank);
287
288             if (isdigit(szHost[0]))
289             {
290                 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
291                     continue;
292             } else {
293                 HOSTENT *pEntry;
294                 if ((pEntry = gethostbyname (szHost)) == NULL)
295                     continue;
296
297                 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
298             }
299             saddr.sin_port = htons(7003);
300             saddr.sin_family = AF_INET;
301             dwRank += (rand() & 0x000f);
302
303             tsp = cm_FindServer(&saddr, CM_SERVER_VLDB);
304             if ( tsp )          /* an existing server - ref count increased */
305             {
306                 lock_ObtainMutex(&tsp->mx);
307                 tsp->ipRank = (USHORT)dwRank;
308                 tsp->flags |= CM_SERVERFLAG_PREF_SET;
309                 tsp->adminRank = tsp->ipRank;
310                 lock_ReleaseMutex(&tsp->mx);
311
312                 /* set preferences for an existing vlserver */
313                 cm_ChangeRankCellVLServer(tsp);
314                 cm_PutServer(tsp);  /* decrease refcount */
315             }
316             else        /* add a new server without a cell */
317             {
318                 tsp = cm_NewServer(&saddr, CM_SERVER_VLDB, NULL, NULL, CM_FLAG_NOPROBE); /* refcount = 1 */
319                 lock_ObtainMutex(&tsp->mx);
320                 tsp->ipRank = (USHORT)dwRank;
321                 tsp->flags |= CM_SERVERFLAG_PREF_SET;
322                 tsp->adminRank = tsp->ipRank;
323                 lock_ReleaseMutex(&tsp->mx);
324             }
325         }
326
327         RegCloseKey(hkPrefs);
328     }
329
330     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
331                       AFSREG_CLT_OPENAFS_SUBKEY "\\Server Preferences\\File",
332                       0,
333                       KEY_READ|KEY_QUERY_VALUE,
334                       &hkPrefs) == ERROR_SUCCESS) {
335
336         RegQueryInfoKey( hkPrefs,
337                          NULL,  /* lpClass */
338                          NULL,  /* lpcClass */
339                          NULL,  /* lpReserved */
340                          NULL,  /* lpcSubKeys */
341                          NULL,  /* lpcMaxSubKeyLen */
342                          NULL,  /* lpcMaxClassLen */
343                          &dwPrefs, /* lpcValues */
344                          NULL,  /* lpcMaxValueNameLen */
345                          NULL,  /* lpcMaxValueLen */
346                          NULL,  /* lpcbSecurityDescriptor */
347                          NULL   /* lpftLastWriteTime */
348                          );
349
350         for ( dwIndex = 0 ; dwIndex < dwPrefs; dwIndex++ ) {
351
352             dwSize = sizeof(DWORD);
353             dwHostSize = 256;
354
355             if (RegEnumValue( hkPrefs, dwIndex, szHost, &dwHostSize, NULL,
356                               &dwType, (LPBYTE)&dwRank, &dwSize))
357             {
358                 afsi_log("RegEnumValue(hkPrefs) failed");
359                 continue;
360             }
361
362             afsi_log("File Server Preference: %s = %d",szHost, dwRank);
363
364             if (isdigit(szHost[0]))
365             {
366                 if ((saddr.sin_addr.S_un.S_addr = inet_addr (szHost)) == INADDR_NONE)
367                     continue;
368             } else {
369                 HOSTENT *pEntry;
370                 if ((pEntry = gethostbyname (szHost)) == NULL)
371                     continue;
372
373                 saddr.sin_addr.S_un.S_addr = *(unsigned long *)pEntry->h_addr;
374             }
375             saddr.sin_port = htons(7000);
376             saddr.sin_family = AF_INET;
377             dwRank += (rand() & 0x000f);
378
379             tsp = cm_FindServer(&saddr, CM_SERVER_FILE);
380             if ( tsp )          /* an existing server - ref count increased */
381             {
382                 lock_ObtainMutex(&tsp->mx);
383                 tsp->ipRank = (USHORT)dwRank;
384                 tsp->flags |= CM_SERVERFLAG_PREF_SET;
385                 tsp->adminRank = tsp->ipRank;
386                 lock_ReleaseMutex(&tsp->mx);
387
388                 /* find volumes which might have RO copy 
389                 /* on server and change the ordering of 
390                  * their RO list 
391                  */
392                 cm_ChangeRankVolume(tsp);
393                 cm_PutServer(tsp);  /* decrease refcount */
394             }
395             else        /* add a new server without a cell */
396             {
397                 tsp = cm_NewServer(&saddr, CM_SERVER_FILE, NULL, NULL, CM_FLAG_NOPROBE); /* refcount = 1 */
398                 lock_ObtainMutex(&tsp->mx);
399                 tsp->ipRank = (USHORT)dwRank;
400                 tsp->flags |= CM_SERVERFLAG_PREF_SET;
401                 tsp->adminRank = tsp->ipRank;
402                 lock_ReleaseMutex(&tsp->mx);
403             }
404         }
405
406         RegCloseKey(hkPrefs);
407     }
408 }
409
410
411 #ifndef _WIN64
412 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
413
414 static BOOL
415 is_wow64(void)
416 {
417     static BOOL bChecked = FALSE;
418     static BOOL bIsWow64 = FALSE;
419
420     if (!bChecked)
421     {
422         HANDLE h1 = NULL;
423         LPFN_ISWOW64PROCESS fnIsWow64Process = NULL;
424
425         h1 = GetModuleHandle("kernel32.dll");
426         fnIsWow64Process =
427             (LPFN_ISWOW64PROCESS)GetProcAddress(h1, "IsWow64Process");
428
429         /* If we don't find the fnIsWow64Process function then we
430          * are not running in a broken Wow64
431          */
432         if (fnIsWow64Process)
433             fnIsWow64Process(GetCurrentProcess(), &bIsWow64);
434
435         bChecked = TRUE;
436     }
437
438     return bIsWow64;
439 }
440 #endif /* _WIN64 */
441
442 /*
443  * AFSD Initialization
444  */
445
446 static int
447 afsd_InitRoot(char **reasonP)
448 {
449     long code;
450     cm_req_t req;
451
452     cm_InitReq(&req);
453
454     if (cm_freelanceEnabled) {
455         cm_FakeRootFid(&cm_data.rootFid);
456     } else {
457         int attempts = 10;
458
459         osi_Log0(afsd_logp, "Loading Root Volume from cell");
460         do {
461             code = cm_FindVolumeByName(cm_data.rootCellp, cm_rootVolumeName, cm_rootUserp,
462                                        &req, CM_GETVOL_FLAG_CREATE, &cm_data.rootVolumep);
463             afsi_log("cm_FindVolumeByName code %x root vol %x", code,
464                       (code ? (cm_volume_t *)-1 : cm_data.rootVolumep));
465         } while (code && --attempts);
466         if (code != 0) {
467             *reasonP = "can't find root volume in root cell";
468             return -1;
469         }
470
471         /* compute the root fid */
472         cm_SetFid(&cm_data.rootFid, cm_data.rootCellp->cellID, cm_GetROVolumeID(cm_data.rootVolumep), 1, 1);
473     }
474
475     code = cm_GetSCache(&cm_data.rootFid, &cm_data.rootSCachep, cm_rootUserp, &req);
476     afsi_log("cm_GetSCache code %x scache %x", code,
477              (code ? (cm_scache_t *)-1 : cm_data.rootSCachep));
478     if (code != 0) {
479         *reasonP = "unknown error";
480         return -1;
481     }
482
483     return 0;
484 }
485
486 int
487 afsd_InitCM(char **reasonP)
488 {
489     osi_uid_t debugID;
490     afs_uint64 cacheBlocks;
491     DWORD cacheSize;
492     DWORD blockSize;
493     long logChunkSize;
494     DWORD stats;
495     DWORD volumes;
496     DWORD cells;
497     DWORD dwValue;
498     DWORD rx_enable_peer_stats;
499     DWORD rx_enable_process_stats;
500     DWORD rx_udpbufsize = -1;
501     DWORD lockOrderValidation;
502     long traceBufSize;
503     long maxcpus;
504     long ltt, ltto;
505     long rx_nojumbo;
506     int  rx_max_rwin_size;
507     int  rx_max_swin_size;
508     int  rx_min_peer_timeout;
509     long virtualCache = 0;
510     fschar_t rootCellName[256];
511     struct rx_service *serverp;
512     static struct rx_securityClass *nullServerSecurityClassp;
513     struct hostent *thp;
514     char *msgBuf;
515     char buf[1024];
516     HKEY parmKey;
517     DWORD dummyLen;
518     DWORD regType;
519     long code;
520     /*int freelanceEnabled;*/
521     WSADATA WSAjunk;
522     int i;
523     int cm_noIPAddr;         /* number of client network interfaces */
524     int cm_IPAddr[CM_MAXINTERFACE_ADDR];    /* client's IP address in host order */
525     int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
526     int cm_NetMtu[CM_MAXINTERFACE_ADDR];    /* client's MTU sizes */
527     int cm_NetFlags[CM_MAXINTERFACE_ADDR];  /* network flags */
528     DWORD dwPriority;
529
530     WSAStartup(0x0101, &WSAjunk);
531
532     init_et_to_sys_error();
533
534     cm_utilsInit();
535
536     /* setup osidebug server at RPC slot 1000 */
537     osi_LongToUID(1000, &debugID);
538     code = osi_InitDebug(&debugID);
539     afsi_log("osi_InitDebug code %d", code);
540
541 #ifndef _WIN64
542     if (is_wow64())
543     {
544         *reasonP = "32-bit OpenAFS Service is incompatible with the WOW64 environment";
545         return -1;
546     }
547 #endif
548
549     //  osi_LockTypeSetDefault("stat"); /* comment this out for speed */
550     if (code != 0) {
551         if (code == RPC_S_NO_PROTSEQS)
552             *reasonP = "No RPC Protocol Sequences registered.  Check HKLM\\SOFTWARE\\Microsoft\\RPC\\ClientProtocols";
553         else
554             *reasonP = "unknown error";
555         return -1;
556     }
557
558     /* who are we ? */
559     gethostname(cm_HostName, sizeof(cm_HostName));
560     afsi_log("gethostname %s", cm_HostName);
561     thp = gethostbyname(cm_HostName);
562     memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
563
564     /* seed random number generator */
565     srand(ntohl(cm_HostAddr));
566
567     /* Look up configuration parameters in Registry */
568     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
569                         0, KEY_QUERY_VALUE, &parmKey);
570     if (code != ERROR_SUCCESS) {
571         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
572                        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
573                        NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
574         StringCbPrintfA(buf, sizeof(buf),
575                          "Failure in configuration while opening Registry: %s",
576                          msgBuf);
577         osi_panic(buf, __FILE__, __LINE__);
578     }
579
580     dummyLen = sizeof(dwPriority);
581     code = RegQueryValueEx(parmKey, "PriorityClass", NULL, NULL,
582                             (BYTE *) &dwPriority, &dummyLen);
583     if (code != ERROR_SUCCESS || dwPriority == 0) {
584         dwPriority = HIGH_PRIORITY_CLASS;
585     }
586     if (dwPriority != GetPriorityClass(GetCurrentProcess()))
587         SetPriorityClass(GetCurrentProcess(), dwPriority);
588     afsi_log("PriorityClass 0x%x", GetPriorityClass(GetCurrentProcess()));
589
590     dummyLen = sizeof(lockOrderValidation);
591     code = RegQueryValueEx(parmKey, "LockOrderValidation", NULL, NULL,
592                             (BYTE *) &lockOrderValidation, &dummyLen);
593     if (code != ERROR_SUCCESS) {
594 #ifdef DEBUG
595         lockOrderValidation = 1;
596 #else
597         lockOrderValidation = 0;
598 #endif
599     }
600     osi_SetLockOrderValidation(lockOrderValidation);
601     afsi_log("Lock Order Validation %s", lockOrderValidation ? "On" : "Off");
602
603     dummyLen = sizeof(maxcpus);
604     code = RegQueryValueEx(parmKey, "MaxCPUs", NULL, NULL,
605                             (BYTE *) &maxcpus, &dummyLen);
606     if (code == ERROR_SUCCESS) {
607         HANDLE hProcess;
608         DWORD_PTR processAffinityMask, systemAffinityMask;
609
610         hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION,
611                                FALSE, GetCurrentProcessId());
612         if ( hProcess != NULL &&
613              GetProcessAffinityMask(hProcess, &processAffinityMask, &systemAffinityMask) )
614         {
615             int i, n, bits;
616             DWORD_PTR mask, newAffinityMask;
617
618 #if defined(_WIN64)
619             bits = 64;
620 #else
621             bits = 32;
622 #endif
623             for ( i=0, n=0, mask=1, newAffinityMask=0; i<bits && n<maxcpus; i++ ) {
624                 if ( processAffinityMask & mask ) {
625                     newAffinityMask |= mask;
626                     n++;
627                 }
628                 mask *= 2;
629             }
630
631             SetProcessAffinityMask(hProcess, newAffinityMask);
632             CloseHandle(hProcess);
633             afsi_log("CPU Restrictions set to %d cpu(s); %d cpu(s) available", maxcpus, n);
634         } else {
635             afsi_log("CPU Restrictions set to %d cpu(s); unable to access process information", maxcpus);
636         }
637     }
638
639     dummyLen = sizeof(TraceOption);
640     code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
641                             (BYTE *) &TraceOption, &dummyLen);
642     afsi_log("Trace Options = %lX", TraceOption);
643
644     dummyLen = sizeof(traceBufSize);
645     code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
646                             (BYTE *) &traceBufSize, &dummyLen);
647     if (code == ERROR_SUCCESS)
648         afsi_log("Trace Buffer size %d", traceBufSize);
649     else {
650         traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
651         afsi_log("Default trace buffer size %d", traceBufSize);
652     }
653
654     /* setup and enable debug log */
655     afsd_logp = osi_LogCreate("afsd", traceBufSize);
656     afsi_log("osi_LogCreate log addr %x", PtrToUlong(afsd_logp));
657     if ((TraceOption & 0x8)
658 #ifdef DEBUG
659          || 1
660 #endif
661          ) {
662         osi_LogEnable(afsd_logp);
663     }
664     logReady = 1;
665
666     osi_Log0(afsd_logp, "Log init");
667
668     dummyLen = sizeof(cacheSize);
669     code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
670                             (BYTE *) &cacheSize, &dummyLen);
671     if (code == ERROR_SUCCESS)
672         afsi_log("Cache size %d", cacheSize);
673     else {
674         cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
675         afsi_log("Default cache size %d", cacheSize);
676     }
677
678     dummyLen = sizeof(logChunkSize);
679     code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
680                             (BYTE *) &logChunkSize, &dummyLen);
681     if (code == ERROR_SUCCESS) {
682         if (logChunkSize < 12 || logChunkSize > 30) {
683             afsi_log("Invalid chunk size %d, using default",
684                       logChunkSize);
685             logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
686         }
687     } else {
688         logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
689     }
690     cm_logChunkSize = logChunkSize;
691     cm_chunkSize = 1 << logChunkSize;
692     afsi_log("Chunk size %u (%d)", cm_chunkSize, cm_logChunkSize);
693
694     dummyLen = sizeof(blockSize);
695     code = RegQueryValueEx(parmKey, "blockSize", NULL, NULL,
696                             (BYTE *) &blockSize, &dummyLen);
697     if (code == ERROR_SUCCESS) {
698         if (blockSize < 1 || 
699             (blockSize > 1024 && (blockSize % CM_CONFIGDEFAULT_BLOCKSIZE != 0))) 
700         {
701             afsi_log("Invalid block size %u specified, using default", blockSize);
702             blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
703         } else {
704             /* 
705              * if the blockSize is less than 1024 we permit the blockSize to be
706              * specified in multiples of the default blocksize
707              */
708             if (blockSize <= 1024)
709                 blockSize *= CM_CONFIGDEFAULT_BLOCKSIZE;
710         }
711     } else {
712         blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
713     }
714     if (blockSize > cm_chunkSize) {
715         afsi_log("Block size (%d) cannot be larger than Chunk size (%d).", 
716                   blockSize, cm_chunkSize);
717         blockSize = cm_chunkSize;
718     }
719     if (cm_chunkSize % blockSize != 0) {
720         afsi_log("Block size (%d) must be a factor of Chunk size (%d).",
721                   blockSize, cm_chunkSize);
722         blockSize = CM_CONFIGDEFAULT_BLOCKSIZE;
723     }
724     afsi_log("Block size %u", blockSize);
725
726     dummyLen = sizeof(numBkgD);
727     code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
728                             (BYTE *) &numBkgD, &dummyLen);
729     if (code == ERROR_SUCCESS) {
730         if (numBkgD > CM_MAX_DAEMONS)
731             numBkgD = CM_MAX_DAEMONS;
732         afsi_log("%d background daemons", numBkgD);
733     } else {
734         numBkgD = CM_CONFIGDEFAULT_DAEMONS;
735         afsi_log("Defaulting to %d background daemons", numBkgD);
736     }
737
738     dummyLen = sizeof(numSvThreads);
739     code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
740                             (BYTE *) &numSvThreads, &dummyLen);
741     if (code == ERROR_SUCCESS)
742         afsi_log("%d server threads", numSvThreads);
743     else {
744         numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
745         afsi_log("Defaulting to %d server threads", numSvThreads);
746     }
747
748     dummyLen = sizeof(stats);
749     code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
750                             (BYTE *) &stats, &dummyLen);
751     if (code == ERROR_SUCCESS)
752         afsi_log("Status cache entries: %d", stats);
753     else {
754         stats = CM_CONFIGDEFAULT_STATS;
755         afsi_log("Default status cache entries: %d", stats);
756     }
757
758     dummyLen = sizeof(volumes);
759     code = RegQueryValueEx(parmKey, "Volumes", NULL, NULL,
760                             (BYTE *) &volumes, &dummyLen);
761     if (code == ERROR_SUCCESS)
762         afsi_log("Volumes cache entries: %d", volumes);
763     else {
764         volumes = CM_CONFIGDEFAULT_STATS / 3;
765         afsi_log("Default volume cache entries: %d", volumes);
766     }
767
768     dummyLen = sizeof(cells);
769     code = RegQueryValueEx(parmKey, "Cells", NULL, NULL,
770                             (BYTE *) &cells, &dummyLen);
771     if (code == ERROR_SUCCESS)
772         afsi_log("Cell cache entries: %d", cells);
773     else {
774         cells = CM_CONFIGDEFAULT_CELLS;
775         afsi_log("Default cell cache entries: %d", cells);
776     }
777
778     dummyLen = sizeof(ltt);
779     code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
780                             (BYTE *) &ltt, &dummyLen);
781     if (code != ERROR_SUCCESS)
782         ltt = 1;
783     smb_LogoffTokenTransfer = ltt;
784     afsi_log("Logoff token transfer %s",  (ltt ? "on" : "off"));
785
786     if (ltt) {
787         dummyLen = sizeof(ltto);
788         code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
789                                 NULL, NULL, (BYTE *) &ltto, &dummyLen);
790         if (code != ERROR_SUCCESS)
791             ltto = 120;
792     } else {
793         ltto = 0;
794     }   
795     smb_LogoffTransferTimeout = ltto;
796     afsi_log("Logoff token transfer timeout %d seconds", ltto);
797
798     dummyLen = sizeof(cm_rootVolumeName);
799     code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
800                             (LPBYTE) cm_rootVolumeName, &dummyLen);
801     if (code == ERROR_SUCCESS)
802         afsi_log("Root volume %s", cm_rootVolumeName);
803     else {
804         cm_FsStrCpy(cm_rootVolumeName, lengthof(cm_rootVolumeName), "root.afs");
805         afsi_log("Default root volume name root.afs");
806     }
807
808     cm_mountRootCLen = sizeof(cm_mountRootC);
809     code = RegQueryValueExW(parmKey, L"MountRoot", NULL, NULL,
810                             (LPBYTE) cm_mountRootC, &cm_mountRootCLen);
811     if (code == ERROR_SUCCESS) {
812         afsi_log("Mount root %S", cm_mountRootC);
813         cm_mountRootCLen = (DWORD)cm_ClientStrLen(cm_mountRootC);
814     } else {
815         cm_ClientStrCpy(cm_mountRootC, lengthof(cm_mountRootC), _C("/afs"));
816         cm_mountRootCLen = (DWORD)cm_ClientStrLen(cm_mountRootC);
817         /* Don't log */
818     }
819
820     cm_ClientStringToFsString(cm_mountRootC, -1, cm_mountRoot, lengthof(cm_mountRoot));
821     cm_mountRootLen = (DWORD)cm_FsStrLen(cm_mountRoot);
822
823     dummyLen = sizeof(buf);
824     code = RegQueryValueEx(parmKey, "CachePath", NULL, &regType,
825                            buf, &dummyLen);
826     if (code == ERROR_SUCCESS && buf[0]) {
827         if (regType == REG_EXPAND_SZ) {
828             dummyLen = ExpandEnvironmentStrings(buf, cm_CachePath, sizeof(cm_CachePath));
829             if (dummyLen > sizeof(cm_CachePath)) {
830                 afsi_log("Cache path [%s] longer than %d after expanding env strings", buf, sizeof(cm_CachePath));
831                 osi_panic("CachePath too long", __FILE__, __LINE__);
832             }
833         } else {
834             StringCbCopyA(cm_CachePath, sizeof(cm_CachePath), buf);
835         }
836         afsi_log("Cache path %s", cm_CachePath);
837     } else {
838         dummyLen = ExpandEnvironmentStrings("%TEMP%\\AFSCache", cm_CachePath, sizeof(cm_CachePath));
839         if (dummyLen > sizeof(cm_CachePath)) {
840             afsi_log("Cache path [%%TEMP%%\\AFSCache] longer than %d after expanding env strings", 
841                      sizeof(cm_CachePath));
842             osi_panic("CachePath too long", __FILE__, __LINE__);
843         }
844         afsi_log("Default cache path %s", cm_CachePath);
845     }
846
847     dummyLen = sizeof(virtualCache);
848     code = RegQueryValueEx(parmKey, "NonPersistentCaching", NULL, NULL,
849                             (LPBYTE)&virtualCache, &dummyLen);
850     afsi_log("Cache type is %s", (virtualCache?"VIRTUAL":"FILE"));
851
852     if (!virtualCache) {
853         dummyLen = sizeof(cm_ValidateCache);
854         code = RegQueryValueEx(parmKey, "ValidateCache", NULL, NULL,
855                                (LPBYTE)&cm_ValidateCache, &dummyLen);
856         if ( cm_ValidateCache < 0 || cm_ValidateCache > 2 )
857             cm_ValidateCache = 1;
858         switch (cm_ValidateCache) {
859         case 0:
860             afsi_log("Cache Validation disabled");
861             break;
862         case 1:
863             afsi_log("Cache Validation on Startup");
864             break;
865         case 2:
866             afsi_log("Cache Validation on Startup and Shutdown");
867             break;
868         }
869     }
870
871     dummyLen = sizeof(traceOnPanic);
872     code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
873                             (BYTE *) &traceOnPanic, &dummyLen);
874     if (code != ERROR_SUCCESS)
875         traceOnPanic = 1;              /* log */
876     afsi_log("Set to %s on panic", traceOnPanic ? "trap" : "not trap");
877
878     dummyLen = sizeof(reportSessionStartups);
879     code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
880                             (BYTE *) &reportSessionStartups, &dummyLen);
881     if (code == ERROR_SUCCESS)
882         afsi_log("Session startups %s be recorded in the Event Log",
883                   reportSessionStartups ? "will" : "will not");
884     else {
885         reportSessionStartups = 0;
886         /* Don't log */
887     }
888
889     for ( i=0; i < MAXNUMSYSNAMES; i++ ) {
890         cm_sysNameList[i] = osi_Alloc(MAXSYSNAME * sizeof(clientchar_t));
891         cm_sysNameList[i][0] = '\0';
892     }
893     cm_sysName = cm_sysNameList[0];
894
895     {
896         clientchar_t *p, *q;
897         clientchar_t * cbuf = (clientchar_t *) buf;
898         dummyLen = sizeof(buf);
899         code = RegQueryValueExW(parmKey, L"SysName", NULL, NULL, (LPBYTE) cbuf, &dummyLen);
900         if (code != ERROR_SUCCESS || !cbuf[0]) {
901 #if defined(_IA64_)
902             cm_ClientStrCpy(cbuf, lengthof(buf), _C("ia64_win64"));
903 #elif defined(_AMD64_)
904             cm_ClientStrCpy(cbuf, lengthof(buf), _C("amd64_win64 x86_win32 i386_w2k"));
905 #else /* assume x86 32-bit */
906             cm_ClientStrCpy(cbuf, lengthof(buf), _C("x86_win32 i386_w2k i386_nt40"));
907 #endif
908         }
909         afsi_log("Sys name %S", cbuf); 
910
911         /* breakup buf into individual search string entries */
912         for (p = q = cbuf; p < cbuf + dummyLen; p++) {
913             if (*p == '\0' || iswspace(*p)) {
914                 memcpy(cm_sysNameList[cm_sysNameCount],q,(p-q) * sizeof(clientchar_t));
915                 cm_sysNameList[cm_sysNameCount][p-q] = '\0';
916                 cm_sysNameCount++;
917                 do {
918                     if (*p == '\0')
919                         goto done_sysname;
920                     p++;
921                 } while (*p == '\0' || isspace(*p));
922                 q = p;
923                 p--;
924             }
925         }
926     }
927   done_sysname:
928     cm_ClientStrCpy(cm_sysName, MAXSYSNAME, cm_sysNameList[0]);
929
930     dummyLen = sizeof(cryptall);
931     code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
932                            (BYTE *) &cryptall, &dummyLen);
933     if (code == ERROR_SUCCESS) {
934         afsi_log("SecurityLevel is %s", cryptall == 1?"crypt": cryptall == 2?"auth":"clear");
935     } else {
936         cryptall = 0;
937         afsi_log("Default SecurityLevel is clear");
938     }
939
940     if (cryptall == 1)
941         LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_ON);
942     else if (cryptall == 2)
943         LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_AUTH);
944     else
945         LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_CRYPT_OFF);
946
947     dummyLen = sizeof(cryptall);
948     code = RegQueryValueEx(parmKey, "ForceAnonVLDB", NULL, NULL,
949                             (BYTE *) &cm_anonvldb, &dummyLen);
950     afsi_log("CM ForceAnonVLDB is %s", cm_anonvldb ? "on" : "off");
951
952     dummyLen = sizeof(cm_dnsEnabled);
953     code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
954                             (BYTE *) &cm_dnsEnabled, &dummyLen);
955     if (code == ERROR_SUCCESS) {
956         afsi_log("DNS %s be used to find AFS cell servers",
957                   cm_dnsEnabled ? "will" : "will not");
958     }       
959     else {
960         cm_dnsEnabled = 1;   /* default on */
961         afsi_log("Default to use DNS to find AFS cell servers");
962     }
963
964 #ifdef AFS_FREELANCE_CLIENT
965     dummyLen = sizeof(cm_freelanceEnabled);
966     code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
967                             (BYTE *) &cm_freelanceEnabled, &dummyLen);
968     if (code == ERROR_SUCCESS) {
969         afsi_log("Freelance client feature %s activated",
970                   cm_freelanceEnabled ? "is" : "is not");
971     }       
972     else {
973         cm_freelanceEnabled = 1;  /* default on */
974     }
975 #endif /* AFS_FREELANCE_CLIENT */
976
977     dummyLen = sizeof(smb_UseUnicode);
978     code = RegQueryValueEx(parmKey, "NegotiateUnicode", NULL, NULL,
979                            (BYTE *) &smb_UseUnicode, &dummyLen);
980     if (code != ERROR_SUCCESS) {
981         smb_UseUnicode = 1; /* default on */
982     }
983     afsi_log("SMB Server Unicode Support is %s",
984               smb_UseUnicode ? "enabled" : "disabled");
985
986     dummyLen = sizeof(smb_hideDotFiles);
987     code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
988                            (BYTE *) &smb_hideDotFiles, &dummyLen);
989     if (code != ERROR_SUCCESS) {
990         smb_hideDotFiles = 1; /* default on */
991     }
992     afsi_log("Dot files/dirs will %sbe marked hidden",
993               smb_hideDotFiles ? "" : "not ");
994
995     dummyLen = sizeof(dwValue);
996     code = RegQueryValueEx(parmKey, "UnixModeFileDefault", NULL, NULL,
997                            (BYTE *) &dwValue, &dummyLen);
998     if (code == ERROR_SUCCESS) {
999         smb_unixModeDefaultFile = (dwValue & 07777);
1000     }
1001     afsi_log("Default unix mode bits for files is 0%04o", smb_unixModeDefaultFile);
1002
1003     dummyLen = sizeof(dwValue);
1004     code = RegQueryValueEx(parmKey, "UnixModeDirDefault", NULL, NULL,
1005                            (BYTE *) &dwValue, &dummyLen);
1006     if (code == ERROR_SUCCESS) {
1007         smb_unixModeDefaultDir = (dwValue & 07777);
1008     }
1009     afsi_log("Default unix mode bits for directories is 0%04o", smb_unixModeDefaultDir);
1010
1011     dummyLen = sizeof(smb_maxMpxRequests);
1012     code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
1013                            (BYTE *) &smb_maxMpxRequests, &dummyLen);
1014     if (code != ERROR_SUCCESS) {
1015         smb_maxMpxRequests = 50;
1016     }
1017     afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
1018
1019     dummyLen = sizeof(smb_maxVCPerServer);
1020     code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
1021                            (BYTE *) &smb_maxVCPerServer, &dummyLen);
1022     if (code != ERROR_SUCCESS) {
1023         smb_maxVCPerServer = 100;
1024     }
1025     afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
1026
1027     dummyLen = sizeof(smb_authType);
1028     code = RegQueryValueEx(parmKey, "SMBAuthType", NULL, NULL,
1029                             (BYTE *) &smb_authType, &dummyLen);
1030
1031     if (code != ERROR_SUCCESS || 
1032          (smb_authType != SMB_AUTH_EXTENDED && smb_authType != SMB_AUTH_NTLM && smb_authType != SMB_AUTH_NONE)) {
1033         smb_authType = SMB_AUTH_EXTENDED; /* default is to use extended authentication */
1034     }
1035     afsi_log("SMB authentication type is %s", ((smb_authType == SMB_AUTH_NONE)?"NONE":((smb_authType == SMB_AUTH_EXTENDED)?"EXTENDED":"NTLM")));
1036
1037     dummyLen = sizeof(rx_max_rwin_size);
1038     code = RegQueryValueEx(parmKey, "RxMaxRecvWinSize", NULL, NULL,
1039                            (BYTE *) &rx_max_rwin_size, &dummyLen);
1040     if (code == ERROR_SUCCESS)
1041         rx_SetMaxReceiveWindow(rx_max_rwin_size);
1042     afsi_log("Rx Maximum Receive Window Size is %d", rx_GetMaxReceiveWindow());
1043
1044     dummyLen = sizeof(rx_max_swin_size);
1045     code = RegQueryValueEx(parmKey, "RxMaxSendWinSize", NULL, NULL,
1046                            (BYTE *) &rx_max_swin_size, &dummyLen);
1047     if (code == ERROR_SUCCESS)
1048         rx_SetMaxSendWindow(rx_max_swin_size);
1049     afsi_log("Rx Maximum Send Window Size is %d", rx_GetMaxSendWindow());
1050
1051     dummyLen = sizeof(rx_min_peer_timeout);
1052     code = RegQueryValueEx(parmKey, "RxMinPeerTimeout", NULL, NULL,
1053                            (BYTE *) &rx_min_peer_timeout, &dummyLen);
1054     if (code == ERROR_SUCCESS)
1055         rx_SetMinPeerTimeout(rx_min_peer_timeout);
1056     afsi_log("Rx Minimum Peer Timeout is %d ms", rx_GetMinPeerTimeout());
1057
1058     dummyLen = sizeof(rx_nojumbo);
1059     code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
1060                            (BYTE *) &rx_nojumbo, &dummyLen);
1061     if (code != ERROR_SUCCESS) {
1062         DWORD jumbo;
1063         dummyLen = sizeof(jumbo);
1064         code = RegQueryValueEx(parmKey, "RxJumbo", NULL, NULL,
1065                                 (BYTE *) &jumbo, &dummyLen);
1066         if (code != ERROR_SUCCESS) {
1067             rx_nojumbo = 1;
1068         } else {
1069             rx_nojumbo = !jumbo;
1070         }
1071     }
1072     if (rx_nojumbo)
1073         afsi_log("RX Jumbograms are disabled");
1074     else
1075         afsi_log("RX Jumbograms are enabled");
1076
1077     dummyLen = sizeof(rx_extraPackets);
1078     code = RegQueryValueEx(parmKey, "RxExtraPackets", NULL, NULL,
1079                            (BYTE *) &rx_extraPackets, &dummyLen);
1080     if (code != ERROR_SUCCESS) {
1081         rx_extraPackets = (numBkgD + numSvThreads + 5) * 64;
1082     }
1083     if (rx_extraPackets)
1084         afsi_log("RX extraPackets is %d", rx_extraPackets);
1085
1086     dummyLen = sizeof(rx_udpbufsize);
1087     code = RegQueryValueEx(parmKey, "RxUdpBufSize", NULL, NULL,
1088                            (BYTE *) &rx_udpbufsize, &dummyLen);
1089     if (code != ERROR_SUCCESS) {
1090         rx_udpbufsize = 256*1024;
1091     }
1092     if (rx_udpbufsize != -1)
1093         afsi_log("RX udpbufsize is %d", rx_udpbufsize);
1094
1095     dummyLen = sizeof(rx_mtu);
1096     code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
1097                            (BYTE *) &rx_mtu, &dummyLen);
1098     if (code != ERROR_SUCCESS || !rx_mtu) {
1099         rx_mtu = -1;
1100     }
1101     if (rx_mtu != -1)
1102         afsi_log("RX maximum MTU is %d", rx_mtu);
1103
1104     dummyLen = sizeof(rx_enable_peer_stats);
1105     code = RegQueryValueEx(parmKey, "RxEnablePeerStats", NULL, NULL,
1106                            (BYTE *) &rx_enable_peer_stats, &dummyLen);
1107     if (code != ERROR_SUCCESS) {
1108         rx_enable_peer_stats = 1;
1109     }
1110     if (rx_enable_peer_stats)
1111         afsi_log("RX Peer Statistics gathering is enabled");
1112     else
1113         afsi_log("RX Peer Statistics gathering is disabled");
1114
1115     dummyLen = sizeof(rx_enable_process_stats);
1116     code = RegQueryValueEx(parmKey, "RxEnableProcessStats", NULL, NULL,
1117                            (BYTE *) &rx_enable_process_stats, &dummyLen);
1118     if (code != ERROR_SUCCESS) {
1119         rx_enable_process_stats = 1;
1120     }
1121     if (rx_enable_process_stats)
1122         afsi_log("RX Process Statistics gathering is enabled");
1123     else
1124         afsi_log("RX Process Statistics gathering is disabled");
1125
1126     dummyLen = sizeof(dwValue);
1127     dwValue = 0;
1128     code = RegQueryValueEx(parmKey, "RxEnableHotThread", NULL, NULL,
1129                             (BYTE *) &dwValue, &dummyLen);
1130      if (code != ERROR_SUCCESS || dwValue != 0) {
1131          rx_EnableHotThread();
1132          afsi_log("RX Hot Thread is enabled");
1133      }
1134      else
1135          afsi_log("RX Hot Thread is disabled");
1136
1137     dummyLen = sizeof(DWORD);
1138     code = RegQueryValueEx(parmKey, "CallBackPort", NULL, NULL,
1139                            (BYTE *) &dwValue, &dummyLen);
1140     if (code == ERROR_SUCCESS) {
1141         cm_callbackport = (unsigned short) dwValue;
1142     }
1143     afsi_log("CM CallBackPort is %u", cm_callbackport);
1144
1145     dummyLen = sizeof(DWORD);
1146     code = RegQueryValueEx(parmKey, "EnableServerLocks", NULL, NULL,
1147                            (BYTE *) &dwValue, &dummyLen);
1148     if (code == ERROR_SUCCESS) {
1149         cm_enableServerLocks = (unsigned short) dwValue;
1150     } 
1151     switch (cm_enableServerLocks) {
1152     case 0:
1153         afsi_log("EnableServerLocks: never");
1154         break;
1155     case 2:
1156         afsi_log("EnableServerLocks: always");
1157         break;
1158     case 1:
1159     default:
1160         afsi_log("EnableServerLocks: server requested");
1161         break;
1162     }
1163
1164     dummyLen = sizeof(DWORD);
1165     code = RegQueryValueEx(parmKey, "DeleteReadOnly", NULL, NULL,
1166                            (BYTE *) &dwValue, &dummyLen);
1167     if (code == ERROR_SUCCESS) {
1168         cm_deleteReadOnly = (unsigned short) dwValue;
1169     } 
1170     afsi_log("CM DeleteReadOnly is %u", cm_deleteReadOnly);
1171     
1172 #ifdef USE_BPLUS
1173     dummyLen = sizeof(DWORD);
1174     code = RegQueryValueEx(parmKey, "BPlusTrees", NULL, NULL,
1175                            (BYTE *) &dwValue, &dummyLen);
1176     if (code == ERROR_SUCCESS) {
1177         cm_BPlusTrees = (unsigned short) dwValue;
1178     } 
1179     afsi_log("CM BPlusTrees is %u", cm_BPlusTrees);
1180
1181     if (cm_BPlusTrees && !cm_InitBPlusDir()) {
1182         cm_BPlusTrees = 0;
1183         afsi_log("CM BPlusTree initialization failure; disabled for this session");
1184     }
1185 #else
1186     afsi_log("CM BPlusTrees is not supported");
1187 #endif
1188
1189     if ((RegQueryValueExW( parmKey, L"PrefetchExecutableExtensions", 0, 
1190                            &regType, NULL, &dummyLen) == ERROR_SUCCESS) &&
1191          (regType == REG_MULTI_SZ)) 
1192     {
1193         clientchar_t * pSz;
1194         dummyLen += 3; /* in case the source string is not nul terminated */
1195         pSz = malloc(dummyLen);
1196         if ((RegQueryValueExW( parmKey, L"PrefetchExecutableExtensions", 0, &regType, 
1197                                (LPBYTE) pSz, &dummyLen) == ERROR_SUCCESS) &&
1198              (regType == REG_MULTI_SZ))
1199         {
1200             int cnt;
1201             clientchar_t * p;
1202
1203             for (cnt = 0, p = pSz; (p - pSz < dummyLen) && *p; cnt++, p += cm_ClientStrLen(p) + 1);
1204
1205             smb_ExecutableExtensions = malloc(sizeof(clientchar_t *) * (cnt+1));
1206
1207             for (cnt = 0, p = pSz; (p - pSz < dummyLen) && *p; cnt++, p += cm_ClientStrLen(p) + 1) {
1208                 smb_ExecutableExtensions[cnt] = p;
1209                 afsi_log("PrefetchExecutableExtension: \"%S\"", p);
1210             }
1211             smb_ExecutableExtensions[cnt] = NULL;
1212         }
1213         
1214         if (!smb_ExecutableExtensions)
1215             free(pSz);
1216     }
1217     if (!smb_ExecutableExtensions)
1218         afsi_log("No PrefetchExecutableExtensions");
1219
1220     dummyLen = sizeof(DWORD);
1221     code = RegQueryValueEx(parmKey, "OfflineReadOnlyIsValid", NULL, NULL,
1222                            (BYTE *) &dwValue, &dummyLen);
1223     if (code == ERROR_SUCCESS) {
1224         cm_OfflineROIsValid = (unsigned short) dwValue;
1225     } 
1226     afsi_log("CM OfflineReadOnlyIsValid is %u", cm_deleteReadOnly);
1227     
1228     dummyLen = sizeof(DWORD);
1229     code = RegQueryValueEx(parmKey, "GiveUpAllCallBacks", NULL, NULL,
1230                            (BYTE *) &dwValue, &dummyLen);
1231     if (code == ERROR_SUCCESS) {
1232         cm_giveUpAllCBs = (unsigned short) dwValue;
1233     } 
1234     afsi_log("CM GiveUpAllCallBacks is %u", cm_giveUpAllCBs);
1235
1236     dummyLen = sizeof(DWORD);
1237     code = RegQueryValueEx(parmKey, "FollowBackupPath", NULL, NULL,
1238                            (BYTE *) &dwValue, &dummyLen);
1239     if (code == ERROR_SUCCESS) {
1240         cm_followBackupPath = (unsigned short) dwValue;
1241     } 
1242     afsi_log("CM FollowBackupPath is %u", cm_followBackupPath);
1243
1244     dummyLen = sizeof(DWORD);
1245     code = RegQueryValueEx(parmKey, "PerFileAccessCheck", NULL, NULL,
1246                            (BYTE *) &dwValue, &dummyLen);
1247     if (code == ERROR_SUCCESS) {
1248         cm_accessPerFileCheck = (int) dwValue;
1249     } 
1250     afsi_log("CM PerFileAccessCheck is %d", cm_accessPerFileCheck);
1251
1252     dummyLen = sizeof(DWORD);
1253     code = RegQueryValueEx(parmKey, "ReadOnlyVolumeVersioning", NULL, NULL,
1254                            (BYTE *) &dwValue, &dummyLen);
1255     if (code == ERROR_SUCCESS) {
1256         cm_readonlyVolumeVersioning = (unsigned short) dwValue;
1257     }
1258     afsi_log("CM ReadOnlyVolumeVersioning is %u", cm_readonlyVolumeVersioning);
1259
1260     RegCloseKey (parmKey);
1261
1262     cacheBlocks = ((afs_uint64)cacheSize * 1024) / blockSize;
1263         
1264     /* get network related info */
1265     cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1266     code = syscfg_GetIFInfo(&cm_noIPAddr,
1267                              cm_IPAddr, cm_SubnetMask,
1268                              cm_NetMtu, cm_NetFlags);
1269
1270     if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
1271         afsi_log("syscfg_GetIFInfo error code %d", code);
1272     else
1273         afsi_log("First Network address %x SubnetMask %x",
1274                   cm_IPAddr[0], cm_SubnetMask[0]);
1275
1276     /*
1277      * Save client configuration for GetCacheConfig requests
1278      */
1279     cm_initParams.nChunkFiles = 0;
1280     cm_initParams.nStatCaches = stats;
1281     cm_initParams.nDataCaches = (afs_uint32)(cacheBlocks > 0xFFFFFFFF ? 0xFFFFFFFF : cacheBlocks);
1282     cm_initParams.nVolumeCaches = volumes;
1283     cm_initParams.firstChunkSize = cm_chunkSize;
1284     cm_initParams.otherChunkSize = cm_chunkSize;
1285     cm_initParams.cacheSize = cacheSize;
1286     cm_initParams.setTime = 0;
1287     cm_initParams.memCache = 1;
1288
1289     /* init user daemon, and other packages */
1290     cm_InitUser();
1291
1292     cm_InitConn();
1293
1294     cm_InitServer();
1295         
1296     cm_InitIoctl();
1297         
1298     smb_InitIoctl();
1299         
1300     cm_InitCallback();
1301
1302     cm_InitNormalization();
1303
1304     code = cm_InitMappedMemory(virtualCache, cm_CachePath, stats, volumes, cells, cm_chunkSize, cacheBlocks, blockSize);
1305     afsi_log("cm_InitMappedMemory code %x", code);
1306     if (code != 0) {
1307         *reasonP = "error initializing cache file";
1308         return -1;
1309     }
1310
1311 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
1312     if (cm_InitDNS(cm_dnsEnabled) == -1)
1313         cm_dnsEnabled = 0;  /* init failed, so deactivate */
1314     afsi_log("cm_InitDNS %d", cm_dnsEnabled);
1315 #endif
1316
1317     /* Set RX parameters before initializing RX */
1318     if ( rx_nojumbo ) {
1319         rx_SetNoJumbo();
1320         afsi_log("rx_SetNoJumbo successful");
1321     }
1322
1323     if ( rx_mtu != -1 ) {
1324         extern void rx_SetMaxMTU(int);
1325
1326         rx_SetMaxMTU(rx_mtu);
1327         afsi_log("rx_SetMaxMTU %d successful", rx_mtu);
1328     }
1329
1330     if ( rx_udpbufsize != -1 ) {
1331         rx_SetUdpBufSize(rx_udpbufsize);
1332         afsi_log("rx_SetUdpBufSize %d", rx_udpbufsize);
1333     }
1334
1335     /* initialize RX, and tell it to listen to the callbackport, 
1336      * which is used for callback RPC messages.
1337      */
1338     code = rx_Init(htons(cm_callbackport));
1339     if (code != 0) {
1340         afsi_log("rx_Init code %x - retrying with a random port number", code);
1341         code = rx_Init(0);
1342     }
1343     afsi_log("rx_Init code %x", code);
1344     if (code != 0) {
1345         *reasonP = "afsd: failed to init rx client";
1346         return -1;
1347     }
1348
1349     /* create an unauthenticated service #1 for callbacks */
1350     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1351     serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
1352                              RXAFSCB_ExecuteRequest);
1353     afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1354     if (serverp == NULL) {
1355         *reasonP = "unknown error";
1356         return -1;
1357     }
1358     rx_SetMinProcs(serverp, 2);
1359     rx_SetMaxProcs(serverp, 4);
1360     rx_SetCheckReach(serverp, 1);
1361
1362     nullServerSecurityClassp = rxnull_NewServerSecurityObject();
1363     serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
1364                              &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
1365     afsi_log("rx_NewService addr %x", PtrToUlong(serverp));
1366     if (serverp == NULL) {
1367         *reasonP = "unknown error";
1368         return -1;
1369     }
1370     rx_SetMinProcs(serverp, 2);
1371     rx_SetMaxProcs(serverp, 4);
1372         
1373     /* start server threads, *not* donating this one to the pool */
1374     rx_StartServer(0);
1375     afsi_log("rx_StartServer");
1376
1377     if (rx_enable_peer_stats)
1378         rx_enablePeerRPCStats();
1379
1380     if (rx_enable_process_stats)
1381         rx_enableProcessRPCStats();
1382
1383     code = cm_GetRootCellName(rootCellName);
1384     afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s", 
1385              code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
1386     if (code != 0 && !cm_freelanceEnabled) 
1387     {
1388         *reasonP = "can't find root cell name in " AFS_CELLSERVDB;
1389         return -1;
1390     }   
1391     else if (cm_freelanceEnabled)
1392         cm_data.rootCellp = NULL;
1393
1394     if (code == 0 && !cm_freelanceEnabled) 
1395     {
1396         cm_data.rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
1397         afsi_log("cm_GetCell addr %x", PtrToUlong(cm_data.rootCellp));
1398         if (cm_data.rootCellp == NULL) 
1399         {
1400             *reasonP = "can't find root cell in " AFS_CELLSERVDB;
1401             return -1;
1402         }
1403     }
1404
1405 #ifdef AFS_FREELANCE_CLIENT
1406     if (cm_freelanceEnabled)
1407         cm_InitFreelance();
1408 #endif
1409
1410     /* Initialize the RPC server for session keys */
1411     RpcInit();
1412
1413     /* Initialize the RPC server for pipe services */
1414     MSRPC_Init();
1415
1416     afsd_InitServerPreferences();
1417
1418     code = afsd_InitRoot(reasonP);
1419
1420     return code;
1421 }
1422
1423 int afsd_ShutdownCM(void)
1424 {
1425     MSRPC_Shutdown();
1426
1427     cm_ReleaseSCache(cm_data.rootSCachep);
1428
1429     cm_utilsCleanup();
1430
1431     cm_shutdown = 1;
1432
1433     return 0;
1434 }
1435
1436 int afsd_InitDaemons(char **reasonP)
1437 {
1438     cm_InitDaemon(numBkgD);
1439     afsi_log("cm_InitDaemon complete");
1440
1441     return 0;
1442 }
1443
1444 int afsd_InitSMB(char **reasonP, void *aMBfunc)
1445 {
1446     HKEY parmKey;
1447     DWORD dummyLen;
1448     DWORD dwValue;
1449     DWORD code;
1450
1451     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1452                          0, KEY_QUERY_VALUE, &parmKey);
1453     if (code == ERROR_SUCCESS) {
1454         dummyLen = sizeof(DWORD);
1455         code = RegQueryValueEx(parmKey, "StoreAnsiFilenames", NULL, NULL,
1456                                 (BYTE *) &dwValue, &dummyLen);
1457         if (code == ERROR_SUCCESS)
1458             smb_StoreAnsiFilenames = dwValue ? 1 : 0;
1459         afsi_log("StoreAnsiFilenames = %d", smb_StoreAnsiFilenames);
1460
1461         dummyLen = sizeof(DWORD);
1462         code = RegQueryValueEx(parmKey, "EnableSMBAsyncStore", NULL, NULL,
1463                                 (BYTE *) &dwValue, &dummyLen);
1464         if (code == ERROR_SUCCESS)
1465             smb_AsyncStore = dwValue == 2 ? 2 : (dwValue ? 1 : 0);
1466         afsi_log("EnableSMBAsyncStore = %d", smb_AsyncStore);
1467
1468         dummyLen = sizeof(DWORD);
1469         code = RegQueryValueEx(parmKey, "SMBAsyncStoreSize", NULL, NULL,
1470                                 (BYTE *) &dwValue, &dummyLen);
1471         if (code == ERROR_SUCCESS) {
1472             /* Should check for >= blocksize && <= chunksize && round down to multiple of blocksize */
1473             if (dwValue > cm_chunkSize)
1474                 smb_AsyncStoreSize = cm_chunkSize;
1475             else if (dwValue <  cm_data.buf_blockSize)
1476                 smb_AsyncStoreSize = cm_data.buf_blockSize;
1477             else
1478                 smb_AsyncStoreSize = (dwValue & ~(cm_data.buf_blockSize-1));
1479         } else 
1480             smb_AsyncStoreSize = CM_CONFIGDEFAULT_ASYNCSTORESIZE;
1481         afsi_log("SMBAsyncStoreSize = %d", smb_AsyncStoreSize);
1482         
1483         RegCloseKey (parmKey);
1484     }
1485
1486     /* Do this last so that we don't handle requests before init is done.
1487      * Here we initialize the SMB listener.
1488      */
1489     smb_Init(afsd_logp, smb_UseV3, numSvThreads, aMBfunc);
1490     afsi_log("smb_Init complete");
1491
1492     return 0;
1493 }
1494
1495 #ifdef ReadOnly
1496 #undef ReadOnly
1497 #endif
1498
1499 #ifdef File
1500 #undef File
1501 #endif
1502
1503 #pragma pack( push, before_imagehlp, 8 )
1504 #include <imagehlp.h>
1505 #pragma pack( pop, before_imagehlp )
1506
1507 #define MAXNAMELEN 1024
1508
1509 void afsd_printStack(HANDLE hThread, CONTEXT *c)
1510 {
1511     HANDLE hProcess = GetCurrentProcess();
1512     int frameNum;
1513 #if defined(_AMD64_)
1514     DWORD64 offset;
1515 #elif defined(_X86_)
1516     DWORD offset;
1517 #endif
1518     DWORD symOptions;
1519     char functionName[MAXNAMELEN];
1520   
1521     IMAGEHLP_MODULE Module;
1522     IMAGEHLP_LINE Line;
1523   
1524     STACKFRAME s;
1525     IMAGEHLP_SYMBOL *pSym;
1526   
1527     afsi_log_useTimestamp = 0;
1528   
1529     pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
1530   
1531     memset( &s, '\0', sizeof s );
1532     if (!SymInitialize(hProcess, NULL, 1) )
1533     {
1534         afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
1535       
1536         SymCleanup( hProcess );
1537         GlobalFree(pSym);
1538       
1539         return;
1540     }
1541   
1542     symOptions = SymGetOptions();
1543     symOptions |= SYMOPT_LOAD_LINES;
1544     symOptions &= ~SYMOPT_UNDNAME;
1545     SymSetOptions( symOptions );
1546   
1547     /*
1548      * init STACKFRAME for first call
1549      * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
1550      * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
1551      * and good riddance.
1552      */
1553 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
1554 #error The STACKFRAME initialization in afsd_printStack() for this platform
1555 #error must be properly configured
1556 #elif defined(_AMD64_)
1557     s.AddrPC.Offset = c->Rip;
1558     s.AddrPC.Mode = AddrModeFlat;
1559     s.AddrFrame.Offset = c->Rbp;
1560     s.AddrFrame.Mode = AddrModeFlat;
1561 #else
1562     s.AddrPC.Offset = c->Eip;
1563     s.AddrPC.Mode = AddrModeFlat;
1564     s.AddrFrame.Offset = c->Ebp;
1565     s.AddrFrame.Mode = AddrModeFlat;
1566 #endif
1567
1568     memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
1569     pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
1570     pSym->MaxNameLength = MAXNAMELEN;
1571   
1572     memset( &Line, '\0', sizeof Line );
1573     Line.SizeOfStruct = sizeof Line;
1574   
1575     memset( &Module, '\0', sizeof Module );
1576     Module.SizeOfStruct = sizeof Module;
1577   
1578     offset = 0;
1579   
1580     afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
1581   
1582     for ( frameNum = 0; ; ++ frameNum )
1583     {
1584         /*
1585          * get next stack frame (StackWalk(), SymFunctionTableAccess(), 
1586          * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
1587          * ERROR_NOACCESS (998), you can assume that either you are done, or
1588          * that the stack is so hosed that the next deeper frame could not be
1589          * found.
1590          */
1591         if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c, 
1592                           NULL, SymFunctionTableAccess, SymGetModuleBase, 
1593                           NULL ) )
1594             break;
1595       
1596         /* display its contents */
1597         afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
1598                  frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
1599                  s.AddrPC.Offset, s.AddrReturn.Offset,
1600                  s.AddrFrame.Offset, s.AddrStack.Offset );
1601       
1602         if ( s.AddrPC.Offset == 0 )
1603         {
1604             afsi_log("(-nosymbols- PC == 0)" );
1605         }
1606         else
1607         { 
1608             /* show procedure info from a valid PC */
1609             if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
1610             {
1611                 if ( GetLastError() != ERROR_INVALID_ADDRESS )
1612                 {
1613                     afsi_log("SymGetSymFromAddr(): errno = %lu", 
1614                              GetLastError());
1615                 }
1616             }
1617             else
1618             {
1619                 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN, 
1620                                      UNDNAME_NAME_ONLY);
1621                 afsi_log("%s", functionName );
1622
1623                 if ( offset != 0 )
1624                 {
1625                     afsi_log(" %+ld bytes", (long) offset);
1626                 }
1627             }
1628
1629             if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
1630             {
1631                 if (GetLastError() != ERROR_INVALID_ADDRESS)
1632                 {
1633                     afsi_log("Error: SymGetLineFromAddr(): errno = %lu", 
1634                              GetLastError());
1635                 }
1636             }
1637             else
1638             {
1639                 afsi_log("    Line: %s(%lu) %+ld bytes", Line.FileName, 
1640                          Line.LineNumber, offset);
1641             }
1642         }
1643       
1644         /* no return address means no deeper stackframe */
1645         if (s.AddrReturn.Offset == 0)
1646         {
1647             SetLastError(0);
1648             break;
1649         }
1650     }
1651   
1652     if (GetLastError() != 0)
1653     {
1654         afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
1655     }
1656   
1657     SymCleanup(hProcess);
1658     GlobalFree(pSym);
1659 }
1660
1661 #ifdef _DEBUG
1662 static DWORD *afsd_crtDbgBreakCurrent = NULL;
1663 static DWORD afsd_crtDbgBreaks[256];
1664 #endif
1665
1666 static EFaultRepRetVal (WINAPI *pReportFault)(LPEXCEPTION_POINTERS pep, DWORD dwMode) = NULL;
1667 static BOOL (WINAPI *pMiniDumpWriteDump)(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,
1668                                   MINIDUMP_TYPE DumpType,
1669                                   PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1670                                   PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1671                                   PMINIDUMP_CALLBACK_INFORMATION CallbackParam) = NULL;
1672
1673
1674 static HANDLE
1675 OpenDumpFile(void)
1676 {
1677     char wd[256];
1678     DWORD code;
1679
1680     code = GetEnvironmentVariable("TEMP", wd, sizeof(wd));
1681     if ( code == 0 || code > sizeof(wd) )
1682     {
1683         if (!GetWindowsDirectory(wd, sizeof(wd)))
1684             return NULL;
1685     }
1686     StringCbCatA(wd, sizeof(wd), "\\afsd.dmp");
1687     return CreateFile( wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1688                             CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
1689 }
1690
1691 void 
1692 GenerateMiniDump(PEXCEPTION_POINTERS ep)
1693 {
1694     if (IsDebuggerPresent())
1695         return;
1696
1697     if (ep == NULL) 
1698     {
1699         // Generate exception to get proper context in dump
1700         __try 
1701         {
1702             RaiseException(DBG_CONTINUE, 0, 0, NULL);
1703         } 
1704         __except(GenerateMiniDump(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION) 
1705         {
1706         }
1707     } 
1708     else
1709     {
1710         MINIDUMP_EXCEPTION_INFORMATION eInfo;
1711         HANDLE hFile = NULL;
1712         HMODULE hDbgHelp = NULL;
1713
1714         hDbgHelp = LoadLibrary("Dbghelp.dll");
1715         if ( hDbgHelp == NULL )
1716             return;
1717
1718         (FARPROC) pMiniDumpWriteDump = GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
1719         if ( pMiniDumpWriteDump == NULL ) {
1720             FreeLibrary(hDbgHelp);
1721             return;
1722         }
1723
1724         hFile = OpenDumpFile();
1725
1726         if ( hFile ) {
1727             HKEY parmKey;
1728             DWORD dummyLen;
1729             DWORD dwValue;
1730             DWORD code;
1731             DWORD dwMiniDumpType = MiniDumpWithDataSegs;
1732
1733             code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
1734                                  0, KEY_QUERY_VALUE, &parmKey);
1735             if (code == ERROR_SUCCESS) {
1736                 dummyLen = sizeof(DWORD);
1737                 code = RegQueryValueEx(parmKey, "MiniDumpType", NULL, NULL,
1738                                         (BYTE *) &dwValue, &dummyLen);
1739                 if (code == ERROR_SUCCESS)
1740                     dwMiniDumpType = dwValue;
1741                 RegCloseKey (parmKey);
1742             }
1743
1744             eInfo.ThreadId = GetCurrentThreadId();
1745             eInfo.ExceptionPointers = ep;
1746             eInfo.ClientPointers = FALSE;
1747
1748             pMiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
1749                                 hFile, dwMiniDumpType, ep ? &eInfo : NULL,
1750                                 NULL, NULL);
1751
1752             CloseHandle(hFile);
1753         }
1754         FreeLibrary(hDbgHelp);
1755     }
1756 }
1757
1758 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
1759 {
1760     CONTEXT context;
1761 #ifdef _DEBUG  
1762     BOOL allocRequestBrk = FALSE;
1763 #endif 
1764     HMODULE hLib = NULL;
1765   
1766     afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n", 
1767              ep->ExceptionRecord->ExceptionCode, 
1768              ep->ExceptionRecord->ExceptionAddress);
1769            
1770 #ifdef _DEBUG
1771     if (afsd_crtDbgBreakCurrent && 
1772         *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
1773     { 
1774         allocRequestBrk = TRUE;
1775         afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
1776     }
1777 #endif
1778            
1779     /* save context if we want to print the stack information */
1780     context = *ep->ContextRecord;
1781            
1782     afsd_printStack(GetCurrentThread(), &context);
1783
1784     GenerateMiniDump(ep);
1785
1786     hLib = LoadLibrary("Faultrep.dll");
1787     if ( hLib ) {
1788         (FARPROC) pReportFault = GetProcAddress(hLib, "ReportFault");
1789         if ( pReportFault )
1790             pReportFault(ep, 0);
1791         FreeLibrary(hLib);
1792     }
1793
1794     if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1795     {
1796         afsi_log("\nEXCEPTION_BREAKPOINT - continue execution ...\n");
1797     
1798 #ifdef _DEBUG
1799         if (allocRequestBrk)
1800         {
1801             afsd_crtDbgBreakCurrent++;
1802             _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
1803         }
1804 #endif         
1805 #if defined(_X86)    
1806         ep->ContextRecord->Eip++;
1807 #endif
1808 #if defined(_AMD64_)
1809         ep->ContextRecord->Rip++;
1810 #endif
1811         return EXCEPTION_CONTINUE_EXECUTION;
1812     }
1813     else
1814     {
1815         return EXCEPTION_CONTINUE_SEARCH;
1816     }
1817 }
1818   
1819 void afsd_SetUnhandledExceptionFilter()
1820 {
1821 #ifndef NOTRACE
1822     SetUnhandledExceptionFilter(afsd_ExceptionFilter);
1823 #endif
1824 }
1825
1826 #ifdef _DEBUG
1827 void afsd_DbgBreakAllocInit()
1828 {
1829     memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
1830     afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
1831 }
1832   
1833 void afsd_DbgBreakAdd(DWORD requestNumber)
1834 {
1835     int i;
1836     for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
1837         {
1838         if (afsd_crtDbgBreaks[i] == -1)
1839             {
1840             break;
1841             }
1842         }
1843     afsd_crtDbgBreaks[i] = requestNumber;
1844
1845     _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);
1846 }
1847 #endif