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