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