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