flushonhibernate-registry-20041017
[openafs.git] / src / WINNT / afsd / afsd_service.c
index 99f7c1a..e260347 100644 (file)
@@ -32,7 +32,8 @@
 // The following is defined if you want to receive Power notifications,
 // including Hibernation, and also subsequent flushing of AFS volumes
 //
-#define REGISTER_POWER_NOTIFICATIONS
+#define REGISTER_POWER_NOTIFICATIONS 1
+#define FLUSH_VOLUME                 1
 //
 // Check
 */
@@ -54,31 +55,33 @@ jmp_buf notifier_jmp;
 extern int traceOnPanic;
 extern HANDLE afsi_file;
 
+int powerEventsRegsitered = 0;
+
 /*
  * Notifier function for use by osi_panic
  */
 static void afsd_notifier(char *msgp, char *filep, long line)
 {
-       char tbuffer[100];
-       char *ptbuf[1];
-       HANDLE h;
+    char tbuffer[512];
+    char *ptbuf[1];
+    HANDLE h;
 
-       if (filep)
-               sprintf(tbuffer, "Error at file %s, line %d: %s",
-                       filep, line, msgp);
-       else
-               sprintf(tbuffer, "Error at unknown location: %s", msgp);
+    if (filep)
+        sprintf(tbuffer, "Error at file %s, line %d: %s",
+                 filep, line, msgp);
+    else
+        sprintf(tbuffer, "Error at unknown location: %s", msgp);
 
-       h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
-       ptbuf[0] = tbuffer;
-       ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, line, NULL, 1, 0, ptbuf, NULL);
-       DeregisterEventSource(h);
+    h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
+    ptbuf[0] = tbuffer;
+    ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, line, NULL, 1, 0, ptbuf, NULL);
+    DeregisterEventSource(h);
 
-       GlobalStatus = line;
+    GlobalStatus = line;
 
-       osi_LogEnable(afsd_logp);
+    osi_LogEnable(afsd_logp);
 
-       afsd_ForceTrace(TRUE);
+    afsd_ForceTrace(TRUE);
 
     afsi_log("--- begin dump ---");
     cm_DumpSCache(afsi_file, "a");
@@ -91,22 +94,22 @@ static void afsd_notifier(char *msgp, char *filep, long line)
     
     DebugBreak();      
 
-       SetEvent(WaitToTerminate);
+    SetEvent(WaitToTerminate);
 
 #ifdef JUMP
-       if (GetCurrentThreadId() == MainThreadId)
-               longjmp(notifier_jmp, 1);
-       else
+    if (GetCurrentThreadId() == MainThreadId)
+        longjmp(notifier_jmp, 1);
+    else
 #endif /* JUMP */
-               ExitThread(1);
+        ExitThread(1);
 }
 
 /*
  * For use miscellaneously in smb.c; need to do better
  */
-static int DummyMessageBox(HWND h, LPCTSTR l1, LPCTSTR l2, UINT ui)
+static int _stdcall DummyMessageBox(HWND h, LPCTSTR l1, LPCTSTR l2, UINT ui)
 {
-       return 0;
+    return 0;
 }
 
 static SERVICE_STATUS          ServiceStatus;
@@ -130,7 +133,6 @@ afsd_ServiceFlushVolume(DWORD dwlpEventData)
     {
         dwRet = NO_ERROR;
     }
-
     else
     {
         /* flush was unsuccessful, or timeout - deny shutdown */
@@ -146,11 +148,65 @@ afsd_ServiceFlushVolume(DWORD dwlpEventData)
     return dwRet;
 }
 
+
+/* service control handler used in nt4 only for backward compat. */
+VOID WINAPI 
+afsd_ServiceControlHandler(DWORD ctrlCode)
+{
+    HKEY parmKey;
+    DWORD dummyLen, doTrace;
+    long code;
+
+    switch (ctrlCode) {
+    case SERVICE_CONTROL_STOP:
+        /* Shutdown RPC */
+        RpcMgmtStopServerListening(NULL);
+
+        /* Force trace if requested */
+        code = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
+                             AFSConfigKeyName,
+                             0, KEY_QUERY_VALUE, &parmKey);
+        if (code != ERROR_SUCCESS)
+            goto doneTrace;
+
+        dummyLen = sizeof(doTrace);
+        code = RegQueryValueEx(parmKey, "TraceOnShutdown",
+                                NULL, NULL,
+                                (BYTE *) &doTrace, &dummyLen);
+        RegCloseKey (parmKey);
+        if (code != ERROR_SUCCESS)
+            doTrace = 0;
+        if (doTrace)
+            afsd_ForceTrace(FALSE);
+
+      doneTrace:
+        ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
+        ServiceStatus.dwWin32ExitCode = NO_ERROR;
+        ServiceStatus.dwCheckPoint = 1;
+        ServiceStatus.dwWaitHint = 10000;
+        ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
+        SetServiceStatus(StatusHandle, &ServiceStatus);
+        SetEvent(WaitToTerminate);
+        break;
+    case SERVICE_CONTROL_INTERROGATE:
+        ServiceStatus.dwCurrentState = SERVICE_RUNNING;
+        ServiceStatus.dwWin32ExitCode = NO_ERROR;
+        ServiceStatus.dwCheckPoint = 0;
+        ServiceStatus.dwWaitHint = 0;
+        ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
+        SetServiceStatus(StatusHandle, &ServiceStatus);
+        break;
+        /* XXX handle system shutdown */
+        /* XXX handle pause & continue */
+    }
+}       
+
+
 /*
 **    Extended ServiceControlHandler that provides Event types
 **    for monitoring Power events, for example.
 */
-DWORD
+DWORD WINAPI
 afsd_ServiceControlHandlerEx(
               DWORD  ctrlCode,
               DWORD  dwEventType,
@@ -158,12 +214,12 @@ afsd_ServiceControlHandlerEx(
               LPVOID lpContext
               )
 {
-       HKEY parmKey;
-       DWORD dummyLen, doTrace;
-       long code;
+    HKEY parmKey;
+    DWORD dummyLen, doTrace;
+    long code;
     DWORD dwRet = ERROR_CALL_NOT_IMPLEMENTED;
 
-       switch (ctrlCode) 
+    switch (ctrlCode) 
     {
     case SERVICE_CONTROL_STOP:
         /* Shutdown RPC */
@@ -207,122 +263,181 @@ afsd_ServiceControlHandlerEx(
         dwRet = NO_ERROR;
         break;
 
-               /* XXX handle system shutdown */
-               /* XXX handle pause & continue */
-               case SERVICE_CONTROL_POWEREVENT:                                              
-               {                                                                                     
-                       /*                                                                                
+        /* XXX handle system shutdown */
+        /* XXX handle pause & continue */
+    case SERVICE_CONTROL_POWEREVENT:                                              
+        {                                                                                     
+            /*                                                                                
             ** dwEventType of this notification == WPARAM of WM_POWERBROADCAST               
-                       **      Return NO_ERROR == return TRUE for that message, i.e. accept request          
-                       **      Return any error code to deny request,                                        
-                       **      i.e. as if returning BROADCAST_QUERY_DENY                                     
-                       */                                                                                
-                       switch((int) dwEventType)                                                         
+            ** Return NO_ERROR == return TRUE for that message, i.e. accept request          
+            ** Return any error code to deny request,                                        
+            ** i.e. as if returning BROADCAST_QUERY_DENY                                     
+            */                                                                                
+            if(powerEventsRegsitered) {
+            switch((int) dwEventType)                                                         
             {                                                                               
-                       case PBT_APMQUERYSUSPEND:                                                         
-                       case PBT_APMQUERYSTANDBY:                                                         
-                                                                                            
-#ifdef REGISTER_POWER_NOTIFICATIONS                                                                  
-                               /* handle event */                                                            
-                               dwRet = afsd_ServiceFlushVolume((DWORD) lpEventData);                         
+            case PBT_APMQUERYSUSPEND:                                                         
+            case PBT_APMQUERYSTANDBY:                                                         
+
+#ifdef FLUSH_VOLUME
+                /* handle event */                                                            
+                dwRet = afsd_ServiceFlushVolume((DWORD) lpEventData);                         
 #else                                                                                       
-                               dwRet = NO_ERROR;                                                             
+                dwRet = NO_ERROR;                                                             
 #endif                                                                                      
-                               break;                                                                        
+                break;                                                                        
                                                                                                                          
-            /* allow remaining case PBT_WhatEver */                                           
-                       case PBT_APMSUSPEND:                                                              
-                       case PBT_APMSTANDBY:                                                              
-                       case PBT_APMRESUMECRITICAL:                                                       
-                       case PBT_APMRESUMESUSPEND:                                                        
-                       case PBT_APMRESUMESTANDBY:                                                        
-                       case PBT_APMBATTERYLOW:                                                           
-                       case PBT_APMPOWERSTATUSCHANGE:                                                    
-                       case PBT_APMOEMEVENT:                                                             
-                       case PBT_APMRESUMEAUTOMATIC:                                                      
-                       default:                                                                          
-                               dwRet = NO_ERROR;                                                             
-            }
+                /* allow remaining case PBT_WhatEver */                                           
+            case PBT_APMSUSPEND:                                                              
+            case PBT_APMSTANDBY:                                                              
+            case PBT_APMRESUMECRITICAL:                                                       
+            case PBT_APMRESUMESUSPEND:                                                        
+            case PBT_APMRESUMESTANDBY:                                                        
+            case PBT_APMBATTERYLOW:                                                           
+            case PBT_APMPOWERSTATUSCHANGE:                                                    
+            case PBT_APMOEMEVENT:                                                             
+            case PBT_APMRESUMEAUTOMATIC:                                                      
+            default:                                                                          
+                dwRet = NO_ERROR;                                                             
+            }   
         }
     }          /* end switch(ctrlCode) */                                                        
-       return dwRet;   
+    return dwRet;   
 }
 
-#if 1
-/* This code was moved to Drivemap.cpp*/
-/* Mount a drive into AFS if the user wants us to */
+/* There is similar code in client_config\drivemap.cpp GlobalMountDrive()
+ * 
+ * Mount a drive into AFS if there global mapping
+ */
 /* DEE Could check first if we are run as SYSTEM */
-void CheckMountDrive()
+#define MAX_RETRIES 30
+static void MountGlobalDrives()
 {
-        char szAfsPath[_MAX_PATH];
-        char szDriveToMapTo[5];
-        DWORD dwResult;
-        char szKeyName[256];
-        HKEY hKey;
-        DWORD dwIndex = 0;
-        DWORD dwDriveSize;
-        DWORD dwSubMountSize;
-        char szSubMount[256];
-        DWORD dwType;
-
-        sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSConfigKeyName);
-
-       dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey);
-       if (dwResult != ERROR_SUCCESS)
-                return;
-
-        while (1) {
-                dwDriveSize = sizeof(szDriveToMapTo);
-                dwSubMountSize = sizeof(szSubMount);
-                dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize, 0, &dwType, szSubMount, &dwSubMountSize);
-                if (dwResult != ERROR_MORE_DATA) {
-                        if (dwResult != ERROR_SUCCESS) {
-                                if (dwResult != ERROR_NO_MORE_ITEMS)
-                                        afsi_log("Failed to read GlobalAutoMapper values: %d\n", dwResult);
-                                break;
-                        }
-                }
-                
-#if 0
-                sprintf(szAfsPath, "\\Device\\LanmanRedirector\\%s\\%s-AFS\\%s", szDriveToMapTo, cm_HostName, szSubMount);
-        
-                dwResult = DefineDosDevice(DDD_RAW_TARGET_PATH, szDriveToMapTo, szAfsPath);
-#else
+    char szAfsPath[_MAX_PATH];
+    char szDriveToMapTo[5];
+    DWORD dwResult;
+    char szKeyName[256];
+    HKEY hKey;
+    DWORD dwIndex = 0, dwRetry = 0;
+    DWORD dwDriveSize;
+    DWORD dwSubMountSize;
+    char szSubMount[256];
+    DWORD dwType;
+
+    sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSConfigKeyName);
+
+    dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey);
+    if (dwResult != ERROR_SUCCESS)
+        return;
+
+    while (dwRetry < MAX_RETRIES) {
+        dwDriveSize = sizeof(szDriveToMapTo);
+        dwSubMountSize = sizeof(szSubMount);
+        dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize, 0, &dwType, szSubMount, &dwSubMountSize);
+        if (dwResult != ERROR_MORE_DATA) {
+            if (dwResult != ERROR_SUCCESS) {
+                if (dwResult != ERROR_NO_MORE_ITEMS)
+                    afsi_log("Failed to read GlobalAutoMapper values: %d\n", dwResult);
+                break;
+            }
+        }
+
+        for ( ; dwRetry < MAX_RETRIES; dwRetry++)
                {
                    NETRESOURCE nr;
                    memset (&nr, 0x00, sizeof(NETRESOURCE));
  
-                   sprintf(szAfsPath,"\\\\%s-AFS\\%s",cm_HostName,szSubMount);
+                   sprintf(szAfsPath,"\\\\%s\\%s",cm_NetbiosName,szSubMount);
                    
-                   nr.dwScope = RESOURCE_GLOBALNET;
+                   nr.dwScope = RESOURCE_GLOBALNET;              /* ignored parameter */
                    nr.dwType=RESOURCETYPE_DISK;
                    nr.lpLocalName=szDriveToMapTo;
                    nr.lpRemoteName=szAfsPath;
-                   nr.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
-                   nr.dwUsage = RESOURCEUSAGE_CONNECTABLE;
+                   nr.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE; /* ignored parameter */
+                   nr.dwUsage = RESOURCEUSAGE_CONNECTABLE;       /* ignored parameter */
+
+                   dwResult = WNetAddConnection2(&nr,NULL,NULL,0);
+            afsi_log("GlobalAutoMap of %s to %s %s (%d)", szDriveToMapTo, szSubMount, 
+                     (dwResult == NO_ERROR) ? "succeeded" : "failed", dwResult);
+            if (dwResult == NO_ERROR) {
+                break;
+            }
+            /* wait for smb server to come up */
+            Sleep((DWORD)1000 /* miliseconds */);              
 
-                   dwResult = WNetAddConnection2(&nr,NULL,NULL,FALSE);
-               }
-#endif
-                afsi_log("GlobalAutoMap of %s to %s %s", szDriveToMapTo, szSubMount, dwResult ? "succeeded" : "failed");
-        }        
+            /* Disconnect any previous mappings */
+            dwResult = WNetCancelConnection2(szDriveToMapTo, 0, TRUE);
+        }
+    }        
 
-        RegCloseKey(hKey);
+    RegCloseKey(hKey);
+}
+
+static void DismountGlobalDrives()
+{
+    char szAfsPath[_MAX_PATH];
+    char szDriveToMapTo[5];
+    DWORD dwResult;
+    char szKeyName[256];
+    HKEY hKey;
+    DWORD dwIndex = 0;
+    DWORD dwDriveSize;
+    DWORD dwSubMountSize;
+    char szSubMount[256];
+    DWORD dwType;
+
+    sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSConfigKeyName);
+
+    dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey);
+    if (dwResult != ERROR_SUCCESS)
+        return;
+
+    while (1) {
+        dwDriveSize = sizeof(szDriveToMapTo);
+        dwSubMountSize = sizeof(szSubMount);
+        dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize, 0, &dwType, szSubMount, &dwSubMountSize);
+        if (dwResult != ERROR_MORE_DATA) {
+            if (dwResult != ERROR_SUCCESS) {
+                if (dwResult != ERROR_NO_MORE_ITEMS)
+                    afsi_log("Failed to read GlobalAutoMapper values: %d\n", dwResult);
+                break;
+            }
+        }
+
+        sprintf(szAfsPath,"\\\\%s\\%s",cm_NetbiosName,szSubMount);
+                   
+        dwResult = WNetCancelConnection2(szDriveToMapTo, 0, TRUE);
+        dwResult = WNetCancelConnection(szAfsPath, TRUE);
+        
+        afsi_log("Disconnect from GlobalAutoMap of %s to %s %s", szDriveToMapTo, szSubMount, dwResult ? "succeeded" : "failed");
+    }        
+
+    RegCloseKey(hKey);
 }
-#endif
 
 typedef BOOL ( APIENTRY * AfsdInitHook )(void);
 #define AFSD_INIT_HOOK "AfsdInitHook"
 #define AFSD_HOOK_DLL  "afsdhook.dll"
 
+/*
+control serviceex exists only on 2000/xp. These functions will be loaded dynamically.
+*/
+
+typedef SERVICE_STATUS_HANDLE ( * RegisterServiceCtrlHandlerExFunc )(  LPCTSTR , LPHANDLER_FUNCTION_EX , LPVOID );
+typedef SERVICE_STATUS_HANDLE ( * RegisterServiceCtrlHandlerFunc   )(  LPCTSTR ,  LPHANDLER_FUNCTION );
+
+RegisterServiceCtrlHandlerExFunc pRegisterServiceCtrlHandlerEx = NULL;
+RegisterServiceCtrlHandlerFunc   pRegisterServiceCtrlHandler   = NULL; 
+
 void afsd_Main(DWORD argc, LPTSTR *argv)
 {
-       long code;
-       char *reason;
+    long code;
+    char *reason;
 #ifdef JUMP
-       int jmpret;
+    int jmpret;
 #endif /* JUMP */
     HANDLE hInitHookDll;
+    HANDLE hAdvApi32;
     AfsdInitHook initHook;
 
 #ifdef _DEBUG
@@ -330,32 +445,45 @@ void afsd_Main(DWORD argc, LPTSTR *argv)
                    _CRTDBG_CHECK_CRT_DF /* | _CRTDBG_DELAY_FREE_MEM_DF */ );
 #endif 
 
-       osi_InitPanic(afsd_notifier);
-       osi_InitTraceOption();
+    osi_InitPanic(afsd_notifier);
+    osi_InitTraceOption();
 
-       GlobalStatus = 0;
+    GlobalStatus = 0;
 
-       afsi_start();
+    afsi_start();
 
-       WaitToTerminate = CreateEvent(NULL, TRUE, FALSE, TEXT("afsd_service_WaitToTerminate"));
+    WaitToTerminate = CreateEvent(NULL, TRUE, FALSE, TEXT("afsd_service_WaitToTerminate"));
     if ( GetLastError() == ERROR_ALREADY_EXISTS )
         afsi_log("Event Object Already Exists: %s", TEXT("afsd_service_WaitToTerminate"));
 
 #ifndef NOTSERVICE
-       StatusHandle = RegisterServiceCtrlHandlerEx(AFS_DAEMON_SERVICE_NAME,
-                       (LPHANDLER_FUNCTION_EX) afsd_ServiceControlHandlerEx,
-                                                 NULL /* user context */
-                                                 );
-
-       ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
-       ServiceStatus.dwServiceSpecificExitCode = 0;
-       ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
-       ServiceStatus.dwWin32ExitCode = NO_ERROR;
-       ServiceStatus.dwCheckPoint = 1;
-       ServiceStatus.dwWaitHint = 30000;
+    hAdvApi32 = LoadLibrary("advapi32.dll");
+    if (hAdvApi32 == NULL)
+    {
+        afsi_log("Fatal: cannot load advapi32.dll");
+        return;
+    }
+
+    pRegisterServiceCtrlHandlerEx = (RegisterServiceCtrlHandlerExFunc)GetProcAddress(hAdvApi32, "RegisterServiceCtrlHandlerExA");
+    if (pRegisterServiceCtrlHandlerEx)
+    {
+        afsi_log("running on 2000+ - using RegisterServiceCtrlHandlerEx");
+        StatusHandle = RegisterServiceCtrlHandlerEx(AFS_DAEMON_SERVICE_NAME, afsd_ServiceControlHandlerEx, NULL );
+    }
+    else
+    {
+        StatusHandle = RegisterServiceCtrlHandler(AFS_DAEMON_SERVICE_NAME, afsd_ServiceControlHandler);
+    }
+
+    ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
+    ServiceStatus.dwServiceSpecificExitCode = 0;
+    ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
+    ServiceStatus.dwWin32ExitCode = NO_ERROR;
+    ServiceStatus.dwCheckPoint = 1;
+    ServiceStatus.dwWaitHint = 30000;
     /* accept Power Events */
-       ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_POWEREVENT;
-       SetServiceStatus(StatusHandle, &ServiceStatus);
+    ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_POWEREVENT;
+    SetServiceStatus(StatusHandle, &ServiceStatus);
 #endif
 
     {       
@@ -367,8 +495,30 @@ void afsd_Main(DWORD argc, LPTSTR *argv)
     }
 
 #ifdef REGISTER_POWER_NOTIFICATIONS
+    {
+        HKEY hkParm;
+        DWORD code;
+        DWORD dummyLen;
+        int bpower = TRUE;
+
+        /* see if we should handle power notifications */
+        code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName, 0, KEY_QUERY_VALUE, &hkParm);
+        if(code == ERROR_SUCCESS) {
+            dummyLen = sizeof(bpower);
+            code = RegQueryValueEx(hkParm, "FlushOnHibernate", NULL, NULL,
+                (BYTE *) &bpower, &dummyLen);      
+
+            if(code != ERROR_SUCCESS)
+                bpower = TRUE;
+
+           RegCloseKey(hkParm);
+        }
     /* create thread used to flush cache */
+        if(bpower) {
     PowerNotificationThreadCreate();
+            powerEventsRegsitered = 1;
+        }
+    }
 #endif
 
     /* allow an exit to be called prior to any initialization */
@@ -382,7 +532,8 @@ void afsd_Main(DWORD argc, LPTSTR *argv)
             hookRc = initHook();
         }
         FreeLibrary(hInitHookDll);
-               
+        hInitHookDll = NULL;
+
         if (hookRc == FALSE)
         {
             ServiceStatus.dwCurrentState = SERVICE_STOPPED;
@@ -412,109 +563,117 @@ void afsd_Main(DWORD argc, LPTSTR *argv)
 
 #ifdef JUMP
     MainThreadId = GetCurrentThreadId();
-       jmpret = setjmp(notifier_jmp);
+    jmpret = setjmp(notifier_jmp);
 
-       if (jmpret == 0) 
+    if (jmpret == 0) 
 #endif /* JUMP */
     {
-               code = afsd_InitCM(&reason);
-               if (code != 0)
-                       osi_panic(reason, __FILE__, __LINE__);
+        code = afsd_InitCM(&reason);
+        if (code != 0) {
+            afsi_log("afsd_InitCM failed: %s (code = %d)", reason, code);
+            osi_panic(reason, __FILE__, __LINE__);
+        }
 
 #ifndef NOTSERVICE
         ServiceStatus.dwCheckPoint++;
         ServiceStatus.dwWaitHint -= 5000;
         SetServiceStatus(StatusHandle, &ServiceStatus);
 #endif
-               code = afsd_InitDaemons(&reason);
-               if (code != 0)
+        code = afsd_InitDaemons(&reason);
+        if (code != 0) {
+            afsi_log("afsd_InitDaemons failed: %s (code = %d)", reason, code);
                        osi_panic(reason, __FILE__, __LINE__);
+        }
 
 #ifndef NOTSERVICE
         ServiceStatus.dwCheckPoint++;
         ServiceStatus.dwWaitHint -= 5000;
         SetServiceStatus(StatusHandle, &ServiceStatus);
 #endif
-               code = afsd_InitSMB(&reason, DummyMessageBox);
-               if (code != 0)
-                       osi_panic(reason, __FILE__, __LINE__);
+        code = afsd_InitSMB(&reason, MessageBox);
+        if (code != 0) {
+            afsi_log("afsd_InitSMB failed: %s (code = %d)", reason, code);
+            osi_panic(reason, __FILE__, __LINE__);
+        }
+
+        MountGlobalDrives();
 
 #ifndef NOTSERVICE
-               ServiceStatus.dwCurrentState = SERVICE_RUNNING;
-               ServiceStatus.dwWin32ExitCode = NO_ERROR;
-               ServiceStatus.dwCheckPoint = 0;
-               ServiceStatus.dwWaitHint = 0;
+        ServiceStatus.dwCurrentState = SERVICE_RUNNING;
+        ServiceStatus.dwWin32ExitCode = NO_ERROR;
+        ServiceStatus.dwCheckPoint = 0;
+        ServiceStatus.dwWaitHint = 0;
 
         /* accept Power events */
-               ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_POWEREVENT;
-               SetServiceStatus(StatusHandle, &ServiceStatus);
-#endif
+        ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_POWEREVENT;
+        SetServiceStatus(StatusHandle, &ServiceStatus);
+#endif  
         {
            HANDLE h; char *ptbuf[1];
-               h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
-               ptbuf[0] = "AFS running";
-               ReportEvent(h, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, ptbuf, NULL);
-               DeregisterEventSource(h);
+            h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
+            ptbuf[0] = "AFS running";
+            ReportEvent(h, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, ptbuf, NULL);
+            DeregisterEventSource(h);
         }
-       }
-
-    /* Check if we should mount a drive into AFS */
-    CheckMountDrive();
+    }
 
-       WaitForSingleObject(WaitToTerminate, INFINITE);
+    WaitForSingleObject(WaitToTerminate, INFINITE);
 
     {   
-    HANDLE h; char *ptbuf[1];
+        HANDLE h; char *ptbuf[1];
        h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
        ptbuf[0] = "AFS quitting";
        ReportEvent(h, GlobalStatus ? EVENTLOG_ERROR_TYPE : EVENTLOG_INFORMATION_TYPE,
                 0, 0, NULL, 1, 0, ptbuf, NULL);
-    DeregisterEventSource(h);
+        DeregisterEventSource(h);
     }
 
+    DismountGlobalDrives();
+    smb_Shutdown();
+    rx_Finalize();
+
 #ifdef REGISTER_POWER_NOTIFICATIONS
-       /* terminate thread used to flush cache */
-       PowerNotificationThreadExit();
+    /* terminate thread used to flush cache */
+    if(powerEventsRegsitered)
+    PowerNotificationThreadExit();
 #endif
 
     /* Remove the ExceptionFilter */
     SetUnhandledExceptionFilter(NULL);
 
-    if ( hInitHookDll )
-        FreeLibrary(hInitHookDll);
-
     ServiceStatus.dwCurrentState = SERVICE_STOPPED;
-       ServiceStatus.dwWin32ExitCode = GlobalStatus ? ERROR_EXCEPTION_IN_SERVICE : NO_ERROR;
-       ServiceStatus.dwCheckPoint = 0;
-       ServiceStatus.dwWaitHint = 0;
-       ServiceStatus.dwControlsAccepted = 0;
-       SetServiceStatus(StatusHandle, &ServiceStatus);
-}
+    ServiceStatus.dwWin32ExitCode = GlobalStatus ? ERROR_EXCEPTION_IN_SERVICE : NO_ERROR;
+    ServiceStatus.dwCheckPoint = 0;
+    ServiceStatus.dwWaitHint = 0;
+    ServiceStatus.dwControlsAccepted = 0;
+    SetServiceStatus(StatusHandle, &ServiceStatus);
+}       
 
 DWORD __stdcall afsdMain_thread(void* notUsed)
 {
-       afsd_Main(0, (LPTSTR*)NULL);
-    exit(0);
+    char * argv[2] = {AFS_DAEMON_SERVICE_NAME, NULL};
+    afsd_Main(1, (LPTSTR*)argv);
+    return(0);
 }
 
 int
 main(void)
 {
-       static SERVICE_TABLE_ENTRY dispatchTable[] = {
-               {AFS_DAEMON_SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) afsd_Main},
-               {NULL, NULL}
-       };
+    static SERVICE_TABLE_ENTRY dispatchTable[] = {
+        {AFS_DAEMON_SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) afsd_Main},
+        {NULL, NULL}
+    };
 
-       if (!StartServiceCtrlDispatcher(dispatchTable))
+    if (!StartServiceCtrlDispatcher(dispatchTable))
     {
         LONG status = GetLastError();
-           if (status == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
+        if (status == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
         {
             DWORD tid;
             hAFSDMainThread = CreateThread(NULL, 0, afsdMain_thread, 0, 0, &tid);
                
             printf("Hit <Enter> to terminate OpenAFS Client Service\n");
-            getchar();              
+            getchar();  
             SetEvent(WaitToTerminate);
         }
     }