Windows: avoid race when writing mountPointString
[openafs.git] / src / WINNT / afsd / cm_daemon.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 #include <roken.h>
13
14 #include <afs/stds.h>
15
16 #include <windows.h>
17 #include <winsock2.h>
18 #include <iphlpapi.h>
19 #include <stdlib.h>
20 #include <malloc.h>
21 #include <string.h>
22
23 #include "afsd.h"
24 #include "smb.h"
25
26 #include <rx/rx.h>
27 #include <rx/rx_prototypes.h>
28 #include <WINNT/afsreg.h>
29
30 #include "afsicf.h"
31
32 /* in seconds */
33 long cm_daemonCheckDownInterval  = 180;
34 long cm_daemonCheckUpInterval    = 240;
35 long cm_daemonCheckVolInterval   = 3600;
36 long cm_daemonCheckCBInterval    = 60;
37 long cm_daemonCheckVolCBInterval = 0;
38 long cm_daemonCheckLockInterval  = 60;
39 long cm_daemonTokenCheckInterval = 180;
40 long cm_daemonCheckOfflineVolInterval = 600;
41 long cm_daemonPerformanceTuningInterval = 0;
42 long cm_daemonRankServerInterval = 600;
43
44 osi_rwlock_t cm_daemonLock;
45
46 long cm_bkgQueueCount;          /* # of queued requests */
47
48 int cm_bkgWaitingForCount;      /* true if someone's waiting for cm_bkgQueueCount to drop */
49
50 cm_bkgRequest_t *cm_bkgListp;           /* first elt in the list of requests */
51 cm_bkgRequest_t *cm_bkgListEndp;        /* last elt in the list of requests */
52
53 extern int powerStateSuspended;
54 int daemon_ShutdownFlag = 0;
55 static int cm_nDaemons = 0;
56 static time_t lastIPAddrChange = 0;
57
58 static EVENT_HANDLE cm_Daemon_ShutdownEvent = NULL;
59 static EVENT_HANDLE cm_IPAddrDaemon_ShutdownEvent = NULL;
60 static EVENT_HANDLE cm_BkgDaemon_ShutdownEvent[CM_MAX_DAEMONS] = 
61        {NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL};
62
63 void cm_IpAddrDaemon(long parm)
64 {
65     extern void smb_CheckVCs(void);
66     char * name = "cm_IPAddrDaemon_ShutdownEvent";
67
68     cm_IPAddrDaemon_ShutdownEvent = thrd_CreateEvent(NULL, FALSE, FALSE, name);
69     if ( GetLastError() == ERROR_ALREADY_EXISTS )
70         afsi_log("Event Object Already Exists: %s", name);
71
72     rx_StartClientThread();
73
74     while (daemon_ShutdownFlag == 0) {
75         DWORD Result;
76         
77         thrd_SetEvent(cm_IPAddrDaemon_ShutdownEvent);
78         Result = NotifyAddrChange(NULL,NULL);
79         if (Result == NO_ERROR && daemon_ShutdownFlag == 0) {
80             lastIPAddrChange = osi_Time();
81             smb_SetLanAdapterChangeDetected();
82             cm_SetLanAdapterChangeDetected();
83             thrd_ResetEvent(cm_IPAddrDaemon_ShutdownEvent);
84         }       
85     }
86
87     thrd_SetEvent(cm_IPAddrDaemon_ShutdownEvent);
88 }
89
90 void cm_BkgDaemon(void * parm)
91 {
92     cm_bkgRequest_t *rp;
93     afs_int32 code;
94     char name[32] = "";
95     long daemonID = (long)(LONG_PTR)parm;
96
97     snprintf(name, sizeof(name), "cm_BkgDaemon_ShutdownEvent%u", daemonID);
98
99     cm_BkgDaemon_ShutdownEvent[daemonID] = thrd_CreateEvent(NULL, FALSE, FALSE, name);
100     if ( GetLastError() == ERROR_ALREADY_EXISTS )
101         afsi_log("Event Object Already Exists: %s", name);
102
103     rx_StartClientThread();
104
105     lock_ObtainWrite(&cm_daemonLock);
106     while (daemon_ShutdownFlag == 0) {
107         if (powerStateSuspended) {
108             Sleep(1000);
109             continue;
110         }
111         if (!cm_bkgListEndp) {
112             osi_SleepW((LONG_PTR)&cm_bkgListp, &cm_daemonLock);
113             lock_ObtainWrite(&cm_daemonLock);
114             continue;
115         }
116                 
117         /* we found a request */
118         for (rp = cm_bkgListEndp; rp; rp = (cm_bkgRequest_t *) osi_QPrev(&rp->q))
119         {
120             if (!(rp->scp->flags & CM_SCACHEFLAG_DATASTORING) &&
121                 cm_ServerAvailable(&rp->scp->fid, rp->userp))
122                 break;
123         }
124         if (rp == NULL) {
125             /* we couldn't find a request that we could process at the current time */
126             lock_ReleaseWrite(&cm_daemonLock);
127             Sleep(1000);
128             lock_ObtainWrite(&cm_daemonLock);
129             continue;
130         }
131
132         osi_QRemoveHT((osi_queue_t **) &cm_bkgListp, (osi_queue_t **) &cm_bkgListEndp, &rp->q);
133         osi_assertx(cm_bkgQueueCount-- > 0, "cm_bkgQueueCount 0");
134         lock_ReleaseWrite(&cm_daemonLock);
135
136         osi_Log1(afsd_logp,"cm_BkgDaemon processing request 0x%p", rp);
137
138 #ifdef DEBUG_REFCOUNT
139         osi_Log2(afsd_logp,"cm_BkgDaemon (before) scp 0x%x ref %d",rp->scp, rp->scp->refCount);
140 #endif
141         code = (*rp->procp)(rp->scp, rp->p1, rp->p2, rp->p3, rp->p4, rp->userp);
142 #ifdef DEBUG_REFCOUNT                
143         osi_Log2(afsd_logp,"cm_BkgDaemon (after) scp 0x%x ref %d",rp->scp, rp->scp->refCount);
144 #endif
145
146         /*
147          * Keep the following list synchronized with the
148          * error code list in cm_BkgStore.  
149          * cm_SyncOpDone(CM_SCACHESYNC_ASYNCSTORE) will be called there unless
150          * one of these errors has occurred.
151          */
152         switch ( code ) {
153         case CM_ERROR_TIMEDOUT: /* or server restarting */
154         case CM_ERROR_RETRY:
155         case CM_ERROR_WOULDBLOCK:
156         case CM_ERROR_ALLBUSY:
157         case CM_ERROR_ALLDOWN:
158         case CM_ERROR_ALLOFFLINE:
159         case CM_ERROR_PARTIALWRITE:
160             if (rp->procp == cm_BkgStore) {
161                 osi_Log2(afsd_logp,
162                          "cm_BkgDaemon re-queueing failed request 0x%p code 0x%x",
163                          rp, code);
164                 lock_ObtainWrite(&cm_daemonLock);
165                 cm_bkgQueueCount++;
166                 osi_QAddT((osi_queue_t **) &cm_bkgListp, (osi_queue_t **)&cm_bkgListEndp, &rp->q);
167                 break;
168             } /* otherwise fall through */
169         case 0:  /* success */
170         default: /* other error */
171             if (code == 0)
172                 osi_Log1(afsd_logp,"cm_BkgDaemon SUCCESS: request 0x%p", rp);
173             else
174                 osi_Log2(afsd_logp,"cm_BkgDaemon FAILED: request dropped 0x%p code 0x%x",
175                          rp, code);
176             cm_ReleaseUser(rp->userp);
177             cm_ReleaseSCache(rp->scp);
178             free(rp);
179             lock_ObtainWrite(&cm_daemonLock);
180         }
181     }
182     lock_ReleaseWrite(&cm_daemonLock);
183     thrd_SetEvent(cm_BkgDaemon_ShutdownEvent[daemonID]);
184 }
185
186 void cm_QueueBKGRequest(cm_scache_t *scp, cm_bkgProc_t *procp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
187         cm_user_t *userp)
188 {
189     cm_bkgRequest_t *rp;
190         
191     rp = malloc(sizeof(*rp));
192     memset(rp, 0, sizeof(*rp));
193         
194     cm_HoldSCache(scp);
195     rp->scp = scp;
196     cm_HoldUser(userp);
197     rp->userp = userp;
198     rp->procp = procp;
199     rp->p1 = p1;
200     rp->p2 = p2;
201     rp->p3 = p3;
202     rp->p4 = p4;
203
204     lock_ObtainWrite(&cm_daemonLock);
205     cm_bkgQueueCount++;
206     osi_QAdd((osi_queue_t **) &cm_bkgListp, &rp->q);
207     if (!cm_bkgListEndp) 
208         cm_bkgListEndp = rp;
209     lock_ReleaseWrite(&cm_daemonLock);
210
211     osi_Wakeup((LONG_PTR) &cm_bkgListp);
212 }
213
214 static int
215 IsWindowsFirewallPresent(void)
216 {
217     SC_HANDLE scm;
218     SC_HANDLE svc;
219     BOOLEAN flag;
220     BOOLEAN result = FALSE;
221     LPQUERY_SERVICE_CONFIG pConfig = NULL;
222     DWORD BufSize;
223     LONG status;
224
225     /* Open services manager */
226     scm = OpenSCManager(NULL, NULL, GENERIC_READ);
227     if (!scm) return FALSE;
228
229     /* Open Windows Firewall service */
230     svc = OpenService(scm, "MpsSvc", SERVICE_QUERY_CONFIG);
231     if (!svc) {
232         afsi_log("MpsSvc Service could not be opened for query: 0x%x", GetLastError());
233         svc = OpenService(scm, "SharedAccess", SERVICE_QUERY_CONFIG);
234         if (!svc)
235             afsi_log("SharedAccess Service could not be opened for query: 0x%x", GetLastError());
236     }
237     if (!svc)
238         goto close_scm;
239
240     /* Query Windows Firewall service config, first just to get buffer size */
241     /* Expected to fail, so don't test return value */
242     (void) QueryServiceConfig(svc, NULL, 0, &BufSize);
243     status = GetLastError();
244     if (status != ERROR_INSUFFICIENT_BUFFER)
245         goto close_svc;
246
247     /* Allocate buffer */
248     pConfig = (LPQUERY_SERVICE_CONFIG)GlobalAlloc(GMEM_FIXED,BufSize);
249     if (!pConfig)
250         goto close_svc;
251
252     /* Query Windows Firewall service config, this time for real */
253     flag = QueryServiceConfig(svc, pConfig, BufSize, &BufSize);
254     if (!flag) {
255         afsi_log("QueryServiceConfig failed: 0x%x", GetLastError());
256         goto free_pConfig;
257     }
258
259     /* Is it autostart? */
260     afsi_log("AutoStart 0x%x", pConfig->dwStartType);
261     if (pConfig->dwStartType < SERVICE_DEMAND_START)
262         result = TRUE;
263
264   free_pConfig:
265     GlobalFree(pConfig);
266   close_svc:
267     CloseServiceHandle(svc);
268   close_scm:
269     CloseServiceHandle(scm);
270
271     return result;
272 }
273
274 void
275 cm_DaemonCheckInit(void)
276 {
277     HKEY parmKey;
278     DWORD dummyLen;
279     DWORD dummy;
280     DWORD code;
281
282     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
283                          0, KEY_QUERY_VALUE, &parmKey);
284     if (code)
285         return;
286
287     dummyLen = sizeof(DWORD);
288     code = RegQueryValueEx(parmKey, "daemonCheckDownInterval", NULL, NULL,
289                             (BYTE *) &dummy, &dummyLen);
290     if (code == ERROR_SUCCESS && dummy)
291         cm_daemonCheckDownInterval = dummy;
292     afsi_log("daemonCheckDownInterval is %d", cm_daemonCheckDownInterval);
293
294     dummyLen = sizeof(DWORD);
295     code = RegQueryValueEx(parmKey, "daemonCheckUpInterval", NULL, NULL,
296                             (BYTE *) &dummy, &dummyLen);
297     if (code == ERROR_SUCCESS && dummy)
298         cm_daemonCheckUpInterval = dummy;
299     afsi_log("daemonCheckUpInterval is %d", cm_daemonCheckUpInterval);
300
301     dummyLen = sizeof(DWORD);
302     code = RegQueryValueEx(parmKey, "daemonCheckVolInterval", NULL, NULL,
303                             (BYTE *) &dummy, &dummyLen);
304     if (code == ERROR_SUCCESS && dummy)
305         cm_daemonCheckVolInterval = dummy;
306     afsi_log("daemonCheckVolInterval is %d", cm_daemonCheckVolInterval);
307
308     dummyLen = sizeof(DWORD);
309     code = RegQueryValueEx(parmKey, "daemonCheckCBInterval", NULL, NULL,
310                             (BYTE *) &dummy, &dummyLen);
311     if (code == ERROR_SUCCESS && dummy)
312         cm_daemonCheckCBInterval = dummy;
313     afsi_log("daemonCheckCBInterval is %d", cm_daemonCheckCBInterval);
314
315     dummyLen = sizeof(DWORD);
316     code = RegQueryValueEx(parmKey, "daemonCheckVolCBInterval", NULL, NULL,
317                             (BYTE *) &dummy, &dummyLen);
318     if (code == ERROR_SUCCESS && dummy)
319         cm_daemonCheckVolCBInterval = dummy;
320     afsi_log("daemonCheckVolCBInterval is %d", cm_daemonCheckVolCBInterval);
321
322     dummyLen = sizeof(DWORD);
323     code = RegQueryValueEx(parmKey, "daemonCheckLockInterval", NULL, NULL,
324                             (BYTE *) &dummy, &dummyLen);
325     if (code == ERROR_SUCCESS && dummy)
326         cm_daemonCheckLockInterval = dummy;
327     afsi_log("daemonCheckLockInterval is %d", cm_daemonCheckLockInterval);
328
329     dummyLen = sizeof(DWORD);
330     code = RegQueryValueEx(parmKey, "daemonCheckTokenInterval", NULL, NULL,
331                             (BYTE *) &dummy, &dummyLen);
332     if (code == ERROR_SUCCESS && dummy)
333         cm_daemonTokenCheckInterval = dummy;
334     afsi_log("daemonCheckTokenInterval is %d", cm_daemonTokenCheckInterval);
335
336     dummyLen = sizeof(DWORD);
337     code = RegQueryValueEx(parmKey, "daemonCheckOfflineVolInterval", NULL, NULL,
338                             (BYTE *) &dummy, &dummyLen);
339     if (code == ERROR_SUCCESS && dummy)
340         cm_daemonCheckOfflineVolInterval = dummy;
341     afsi_log("daemonCheckOfflineVolInterval is %d", cm_daemonCheckOfflineVolInterval);
342     
343     dummyLen = sizeof(DWORD);
344     code = RegQueryValueEx(parmKey, "daemonPerformanceTuningInterval", NULL, NULL,
345                             (BYTE *) &dummy, &dummyLen);
346     if (code == ERROR_SUCCESS)
347         cm_daemonPerformanceTuningInterval = dummy;
348     afsi_log("daemonPerformanceTuningInterval is %d", cm_daemonPerformanceTuningInterval);
349
350     dummyLen = sizeof(DWORD);
351     code = RegQueryValueEx(parmKey, "daemonRankServerInterval", NULL, NULL,
352                             (BYTE *) &dummy, &dummyLen);
353     if (code == ERROR_SUCCESS && dummy)
354         cm_daemonRankServerInterval = dummy;
355     afsi_log("daemonRankServerInterval is %d", cm_daemonRankServerInterval);
356
357     RegCloseKey(parmKey);
358
359     if (cm_daemonPerformanceTuningInterval)
360         cm_PerformanceTuningInit();
361 }
362
363 /* periodic check daemon */
364 void cm_Daemon(long parm)
365 {
366     time_t now;
367     time_t lastLockCheck;
368     time_t lastVolCheck;
369     time_t lastCBExpirationCheck;
370     time_t lastVolCBRenewalCheck;
371     time_t lastDownServerCheck;
372     time_t lastUpServerCheck;
373     time_t lastTokenCacheCheck;
374     time_t lastBusyVolCheck;
375     time_t lastPerformanceCheck;
376     time_t lastServerRankCheck;
377     char thostName[200];
378     unsigned long code;
379     struct hostent *thp;
380     HMODULE hHookDll;
381     char * name = "cm_Daemon_ShutdownEvent";
382     int configureFirewall = IsWindowsFirewallPresent();
383     int bAddrChangeCheck = 0;
384
385     cm_Daemon_ShutdownEvent = thrd_CreateEvent(NULL, FALSE, FALSE, name);
386     if ( GetLastError() == ERROR_ALREADY_EXISTS )
387         afsi_log("Event Object Already Exists: %s", name);
388
389     if (!configureFirewall) {
390         afsi_log("No Windows Firewall detected");
391     }
392
393     if (cm_freelanceEnabled && cm_freelanceImportCellServDB)
394         cm_FreelanceImportCellServDB();
395
396     /* ping all file servers, up or down, with unauthenticated connection,
397      * to find out whether we have all our callbacks from the server still.
398      * Also, ping down VLDBs.
399      */
400     /*
401      * Seed the random number generator with our own address, so that
402      * clients starting at the same time don't all do vol checks at the
403      * same time.
404      */
405     gethostname(thostName, sizeof(thostName));
406     thp = gethostbyname(thostName);
407     if (thp == NULL)    /* In djgpp, gethostname returns the netbios
408                            name of the machine.  gethostbyname will fail
409                            looking this up if it differs from DNS name. */
410         code = 0;
411     else
412         memcpy(&code, thp->h_addr_list[0], 4);
413     
414     srand(ntohl(code));
415
416     cm_DaemonCheckInit();
417
418     now = osi_Time();
419     lastVolCheck = now - cm_daemonCheckVolInterval/2 + (rand() % cm_daemonCheckVolInterval);
420     lastCBExpirationCheck = now - cm_daemonCheckCBInterval/2 + (rand() % cm_daemonCheckCBInterval);
421     if (cm_daemonCheckVolCBInterval)
422         lastVolCBRenewalCheck = now - cm_daemonCheckVolCBInterval/2 + (rand() % cm_daemonCheckVolCBInterval);
423     lastLockCheck = now - cm_daemonCheckLockInterval/2 + (rand() % cm_daemonCheckLockInterval);
424     lastDownServerCheck = now - cm_daemonCheckDownInterval/2 + (rand() % cm_daemonCheckDownInterval);
425     lastUpServerCheck = now - cm_daemonCheckUpInterval/2 + (rand() % cm_daemonCheckUpInterval);
426     lastTokenCacheCheck = now - cm_daemonTokenCheckInterval/2 + (rand() % cm_daemonTokenCheckInterval);
427     lastBusyVolCheck = now - cm_daemonCheckOfflineVolInterval/2 * (rand() % cm_daemonCheckOfflineVolInterval);
428     if (cm_daemonPerformanceTuningInterval)
429         lastPerformanceCheck = now - cm_daemonPerformanceTuningInterval/2 * (rand() % cm_daemonPerformanceTuningInterval);
430     lastServerRankCheck = now - cm_daemonRankServerInterval/2 * (rand() % cm_daemonRankServerInterval);
431
432     while (daemon_ShutdownFlag == 0) {
433         if (powerStateSuspended) {
434             Sleep(1000);
435             continue;
436         }
437         /* check to see if the listener threads halted due to network 
438          * disconnect or other issues.  If so, attempt to restart them.
439          */
440         smb_RestartListeners(0);
441
442         if (daemon_ShutdownFlag == 1)
443             break;
444
445         if (configureFirewall) {
446             /* Open Microsoft Firewall to allow in port 7001 */
447             switch (icf_CheckAndAddAFSPorts(AFS_PORTSET_CLIENT)) {
448             case 0:
449                 afsi_log("Windows Firewall Configuration succeeded");
450                 configureFirewall = 0;
451                 break;
452             case 1:
453                 afsi_log("Invalid Windows Firewall Port Set");
454                 break;
455             case 2:
456                 afsi_log("Unable to open Windows Firewall Profile");
457                 break;
458             case 3:
459                 afsi_log("Unable to create/modify Windows Firewall Port entries");
460                 break;
461             default:
462                 afsi_log("Unknown Windows Firewall Configuration error");
463             }
464         }
465
466         /* find out what time it is */
467         now = osi_Time();
468
469         /* Determine whether an address change took place that we need to respond to */
470         if (bAddrChangeCheck)
471             bAddrChangeCheck = 0;
472
473         if (lastIPAddrChange != 0 && lastIPAddrChange + 2500 < now) {
474             bAddrChangeCheck = 1;
475             lastIPAddrChange = 0;
476         }
477
478         /* check down servers */
479         if ((bAddrChangeCheck || now > lastDownServerCheck + cm_daemonCheckDownInterval) &&
480             daemon_ShutdownFlag == 0 &&
481             powerStateSuspended == 0) {
482             lastDownServerCheck = now;
483             osi_Log0(afsd_logp, "cm_Daemon CheckDownServers");
484             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, NULL);
485             if (daemon_ShutdownFlag == 1)
486                 break;
487             now = osi_Time();
488         }
489
490         if (bAddrChangeCheck &&
491             daemon_ShutdownFlag == 0 &&
492             powerStateSuspended == 0)
493             cm_ForceNewConnectionsAllServers();
494
495         /* check up servers */
496         if ((bAddrChangeCheck || now > lastUpServerCheck + cm_daemonCheckUpInterval) &&
497             daemon_ShutdownFlag == 0 &&
498             powerStateSuspended == 0) {
499             lastUpServerCheck = now;
500             osi_Log0(afsd_logp, "cm_Daemon CheckUpServers");
501             cm_CheckServers(CM_FLAG_CHECKUPSERVERS, NULL);
502             if (daemon_ShutdownFlag == 1)
503                 break;
504             now = osi_Time();
505         }
506
507         if (bAddrChangeCheck &&
508             daemon_ShutdownFlag == 0 &&
509             powerStateSuspended == 0) {
510             smb_CheckVCs();
511             cm_VolStatus_Network_Addr_Change();
512         }
513
514         /*
515          * Once every five minutes inspect the volume list and enforce
516          * the volume location expiration time.
517          */
518         if (now > lastVolCheck + 300 &&
519             daemon_ShutdownFlag == 0 &&
520             powerStateSuspended == 0) {
521             lastVolCheck = now;
522             cm_RefreshVolumes(cm_daemonCheckVolInterval);
523             if (daemon_ShutdownFlag == 1)
524                 break;
525             now = osi_Time();
526         }
527
528         /* Rank all up servers */
529         if ((now > lastServerRankCheck + cm_daemonRankServerInterval) &&
530             daemon_ShutdownFlag == 0 &&
531             powerStateSuspended == 0) {
532             lastServerRankCheck = now;
533             osi_Log0(afsd_logp, "cm_Daemon RankServer");
534             cm_RankUpServers();
535             if(daemon_ShutdownFlag == 1)
536                 break;
537             now = osi_Time();
538         }
539
540         if (cm_daemonCheckVolCBInterval && 
541             now > lastVolCBRenewalCheck + cm_daemonCheckVolCBInterval &&
542             daemon_ShutdownFlag == 0 &&
543             powerStateSuspended == 0) {
544             lastVolCBRenewalCheck = now;
545             cm_VolumeRenewROCallbacks();
546             if (daemon_ShutdownFlag == 1)
547                 break;
548             now = osi_Time();
549         }
550
551         if ((bAddrChangeCheck || now > lastBusyVolCheck + cm_daemonCheckOfflineVolInterval) &&
552             daemon_ShutdownFlag == 0 &&
553             powerStateSuspended == 0) {
554             lastVolCheck = now;
555             cm_CheckOfflineVolumes();
556             if (daemon_ShutdownFlag == 1)
557                 break;
558             now = osi_Time();
559         }
560
561         if (now > lastCBExpirationCheck + cm_daemonCheckCBInterval &&
562             daemon_ShutdownFlag == 0 &&
563             powerStateSuspended == 0) {
564             lastCBExpirationCheck = now;
565             cm_CheckCBExpiration();
566             if (daemon_ShutdownFlag == 1)
567                 break;
568             now = osi_Time();
569         }
570
571         if (now > lastLockCheck + cm_daemonCheckLockInterval &&
572             daemon_ShutdownFlag == 0 &&
573             powerStateSuspended == 0) {
574             lastLockCheck = now;
575             cm_CheckLocks();
576             if (daemon_ShutdownFlag == 1)
577                 break;
578             now = osi_Time();
579         }
580
581         if (now > lastTokenCacheCheck + cm_daemonTokenCheckInterval &&
582             daemon_ShutdownFlag == 0 &&
583             powerStateSuspended == 0) {
584             lastTokenCacheCheck = now;
585             cm_CheckTokenCache(now);
586             if (daemon_ShutdownFlag == 1)
587                 break;
588             now = osi_Time();
589         }
590
591         /* allow an exit to be called prior to stopping the service */
592         hHookDll = cm_LoadAfsdHookLib();
593         if (hHookDll)
594         {
595             BOOL hookRc = TRUE;
596             AfsdDaemonHook daemonHook = ( AfsdDaemonHook ) GetProcAddress(hHookDll, AFSD_DAEMON_HOOK);
597             if (daemonHook)
598             {
599                 hookRc = daemonHook();
600             }
601             FreeLibrary(hHookDll);
602             hHookDll = NULL;
603
604             if (hookRc == FALSE)
605             {
606                 SetEvent(WaitToTerminate);
607             }
608
609             if (daemon_ShutdownFlag == 1) {
610                 break;
611             }
612             now = osi_Time();
613         }
614
615         if (cm_daemonPerformanceTuningInterval &&
616             now > lastPerformanceCheck + cm_daemonPerformanceTuningInterval &&
617             daemon_ShutdownFlag == 0 &&
618             powerStateSuspended == 0) {
619             lastPerformanceCheck = now;
620             cm_PerformanceTuningCheck();
621             if (daemon_ShutdownFlag == 1)
622                 break;
623             now = osi_Time();
624         }
625         
626         thrd_Sleep(10000);              /* sleep 10 seconds */
627     }
628     thrd_SetEvent(cm_Daemon_ShutdownEvent);
629 }       
630
631 void cm_DaemonShutdown(void)
632 {
633     int i;
634     DWORD code;
635
636     daemon_ShutdownFlag = 1;
637     osi_Wakeup((LONG_PTR) &cm_bkgListp);
638
639     /* wait for shutdown */
640     if (cm_Daemon_ShutdownEvent)
641         code = thrd_WaitForSingleObject_Event(cm_Daemon_ShutdownEvent, INFINITE); 
642
643     for ( i=0; i<cm_nDaemons; i++) {
644         if (cm_BkgDaemon_ShutdownEvent[i])
645             code = thrd_WaitForSingleObject_Event(cm_BkgDaemon_ShutdownEvent[i], INFINITE);
646     }
647
648     if (cm_IPAddrDaemon_ShutdownEvent)
649         code = thrd_WaitForSingleObject_Event(cm_IPAddrDaemon_ShutdownEvent, INFINITE);
650 }
651
652 void cm_InitDaemon(int nDaemons)
653 {
654     static osi_once_t once;
655     long pid;
656     thread_t phandle;
657     int i;
658
659     cm_nDaemons = (nDaemons > CM_MAX_DAEMONS) ? CM_MAX_DAEMONS : nDaemons;
660     
661     if (osi_Once(&once)) {
662         lock_InitializeRWLock(&cm_daemonLock, "cm_daemonLock", 
663                                LOCK_HIERARCHY_DAEMON_GLOBAL);
664         osi_EndOnce(&once);
665
666         /* creating IP Address Change monitor daemon */
667         phandle = thrd_Create((SecurityAttrib) 0, 0,
668                                (ThreadFunc) cm_IpAddrDaemon, 0, 0, &pid, "cm_IpAddrDaemon");
669         osi_assertx(phandle != NULL, "cm_IpAddrDaemon thread creation failure");
670         thrd_CloseHandle(phandle);
671
672         /* creating pinging daemon */
673         phandle = thrd_Create((SecurityAttrib) 0, 0,
674                                (ThreadFunc) cm_Daemon, 0, 0, &pid, "cm_Daemon");
675         osi_assertx(phandle != NULL, "cm_Daemon thread creation failure");
676         thrd_CloseHandle(phandle);
677
678         for(i=0; i < cm_nDaemons; i++) {
679             phandle = thrd_Create((SecurityAttrib) 0, 0,
680                                    (ThreadFunc) cm_BkgDaemon, (LPVOID)(LONG_PTR)i, 0, &pid,
681                                    "cm_BkgDaemon");
682             osi_assertx(phandle != NULL, "cm_BkgDaemon thread creation failure");
683             thrd_CloseHandle(phandle);
684         }
685     }
686 }