Windows: cm_BkgDaemon requeuing only applies to BkgStore
[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             if (rp->procp == cm_BkgStore) {
157                 osi_Log2(afsd_logp,
158                          "cm_BkgDaemon re-queueing failed request 0x%p code 0x%x",
159                          rp, code);
160                 lock_ObtainWrite(&cm_daemonLock);
161                 cm_bkgQueueCount++;
162                 osi_QAddT((osi_queue_t **) &cm_bkgListp, (osi_queue_t **)&cm_bkgListEndp, &rp->q);
163                 break;
164             } /* otherwise fall through */
165         case 0:  /* success */
166         default: /* other error */
167             if (code == 0)
168                 osi_Log1(afsd_logp,"cm_BkgDaemon SUCCESS: request 0x%p", rp);
169             else
170                 osi_Log2(afsd_logp,"cm_BkgDaemon FAILED: request dropped 0x%p code 0x%x",
171                          rp, code);
172             cm_ReleaseUser(rp->userp);
173             cm_ReleaseSCache(rp->scp);
174             free(rp);
175             lock_ObtainWrite(&cm_daemonLock);
176         }
177     }
178     lock_ReleaseWrite(&cm_daemonLock);
179     thrd_SetEvent(cm_BkgDaemon_ShutdownEvent[daemonID]);
180 }
181
182 void cm_QueueBKGRequest(cm_scache_t *scp, cm_bkgProc_t *procp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
183         cm_user_t *userp)
184 {
185     cm_bkgRequest_t *rp;
186         
187     rp = malloc(sizeof(*rp));
188     memset(rp, 0, sizeof(*rp));
189         
190     cm_HoldSCache(scp);
191     rp->scp = scp;
192     cm_HoldUser(userp);
193     rp->userp = userp;
194     rp->procp = procp;
195     rp->p1 = p1;
196     rp->p2 = p2;
197     rp->p3 = p3;
198     rp->p4 = p4;
199
200     lock_ObtainWrite(&cm_daemonLock);
201     cm_bkgQueueCount++;
202     osi_QAdd((osi_queue_t **) &cm_bkgListp, &rp->q);
203     if (!cm_bkgListEndp) 
204         cm_bkgListEndp = rp;
205     lock_ReleaseWrite(&cm_daemonLock);
206
207     osi_Wakeup((LONG_PTR) &cm_bkgListp);
208 }
209
210 static int
211 IsWindowsFirewallPresent(void)
212 {
213     SC_HANDLE scm;
214     SC_HANDLE svc;
215     BOOLEAN flag;
216     BOOLEAN result = FALSE;
217     LPQUERY_SERVICE_CONFIG pConfig = NULL;
218     DWORD BufSize;
219     LONG status;
220
221     /* Open services manager */
222     scm = OpenSCManager(NULL, NULL, GENERIC_READ);
223     if (!scm) return FALSE;
224
225     /* Open Windows Firewall service */
226     svc = OpenService(scm, "MpsSvc", SERVICE_QUERY_CONFIG);
227     if (!svc) {
228         afsi_log("MpsSvc Service could not be opened for query: 0x%x", GetLastError());
229         svc = OpenService(scm, "SharedAccess", SERVICE_QUERY_CONFIG);
230         if (!svc)
231             afsi_log("SharedAccess Service could not be opened for query: 0x%x", GetLastError());
232     }
233     if (!svc)
234         goto close_scm;
235
236     /* Query Windows Firewall service config, first just to get buffer size */
237     /* Expected to fail, so don't test return value */
238     (void) QueryServiceConfig(svc, NULL, 0, &BufSize);
239     status = GetLastError();
240     if (status != ERROR_INSUFFICIENT_BUFFER)
241         goto close_svc;
242
243     /* Allocate buffer */
244     pConfig = (LPQUERY_SERVICE_CONFIG)GlobalAlloc(GMEM_FIXED,BufSize);
245     if (!pConfig)
246         goto close_svc;
247
248     /* Query Windows Firewall service config, this time for real */
249     flag = QueryServiceConfig(svc, pConfig, BufSize, &BufSize);
250     if (!flag) {
251         afsi_log("QueryServiceConfig failed: 0x%x", GetLastError());
252         goto free_pConfig;
253     }
254
255     /* Is it autostart? */
256     afsi_log("AutoStart 0x%x", pConfig->dwStartType);
257     if (pConfig->dwStartType < SERVICE_DEMAND_START)
258         result = TRUE;
259
260   free_pConfig:
261     GlobalFree(pConfig);
262   close_svc:
263     CloseServiceHandle(svc);
264   close_scm:
265     CloseServiceHandle(scm);
266
267     return result;
268 }
269
270 void
271 cm_DaemonCheckInit(void)
272 {
273     HKEY parmKey;
274     DWORD dummyLen;
275     DWORD dummy;
276     DWORD code;
277
278     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
279                          0, KEY_QUERY_VALUE, &parmKey);
280     if (code)
281         return;
282
283     dummyLen = sizeof(DWORD);
284     code = RegQueryValueEx(parmKey, "daemonCheckDownInterval", NULL, NULL,
285                             (BYTE *) &dummy, &dummyLen);
286     if (code == ERROR_SUCCESS && dummy)
287         cm_daemonCheckDownInterval = dummy;
288     afsi_log("daemonCheckDownInterval is %d", cm_daemonCheckDownInterval);
289
290     dummyLen = sizeof(DWORD);
291     code = RegQueryValueEx(parmKey, "daemonCheckUpInterval", NULL, NULL,
292                             (BYTE *) &dummy, &dummyLen);
293     if (code == ERROR_SUCCESS && dummy)
294         cm_daemonCheckUpInterval = dummy;
295     afsi_log("daemonCheckUpInterval is %d", cm_daemonCheckUpInterval);
296
297     dummyLen = sizeof(DWORD);
298     code = RegQueryValueEx(parmKey, "daemonCheckVolInterval", NULL, NULL,
299                             (BYTE *) &dummy, &dummyLen);
300     if (code == ERROR_SUCCESS && dummy)
301         cm_daemonCheckVolInterval = dummy;
302     afsi_log("daemonCheckVolInterval is %d", cm_daemonCheckVolInterval);
303
304     dummyLen = sizeof(DWORD);
305     code = RegQueryValueEx(parmKey, "daemonCheckCBInterval", NULL, NULL,
306                             (BYTE *) &dummy, &dummyLen);
307     if (code == ERROR_SUCCESS && dummy)
308         cm_daemonCheckCBInterval = dummy;
309     afsi_log("daemonCheckCBInterval is %d", cm_daemonCheckCBInterval);
310
311     dummyLen = sizeof(DWORD);
312     code = RegQueryValueEx(parmKey, "daemonCheckVolCBInterval", NULL, NULL,
313                             (BYTE *) &dummy, &dummyLen);
314     if (code == ERROR_SUCCESS && dummy)
315         cm_daemonCheckVolCBInterval = dummy;
316     afsi_log("daemonCheckVolCBInterval is %d", cm_daemonCheckVolCBInterval);
317
318     dummyLen = sizeof(DWORD);
319     code = RegQueryValueEx(parmKey, "daemonCheckLockInterval", NULL, NULL,
320                             (BYTE *) &dummy, &dummyLen);
321     if (code == ERROR_SUCCESS && dummy)
322         cm_daemonCheckLockInterval = dummy;
323     afsi_log("daemonCheckLockInterval is %d", cm_daemonCheckLockInterval);
324
325     dummyLen = sizeof(DWORD);
326     code = RegQueryValueEx(parmKey, "daemonCheckTokenInterval", NULL, NULL,
327                             (BYTE *) &dummy, &dummyLen);
328     if (code == ERROR_SUCCESS && dummy)
329         cm_daemonTokenCheckInterval = dummy;
330     afsi_log("daemonCheckTokenInterval is %d", cm_daemonTokenCheckInterval);
331
332     dummyLen = sizeof(DWORD);
333     code = RegQueryValueEx(parmKey, "daemonCheckOfflineVolInterval", NULL, NULL,
334                             (BYTE *) &dummy, &dummyLen);
335     if (code == ERROR_SUCCESS && dummy)
336         cm_daemonCheckOfflineVolInterval = dummy;
337     afsi_log("daemonCheckOfflineVolInterval is %d", cm_daemonCheckOfflineVolInterval);
338     
339     dummyLen = sizeof(DWORD);
340     code = RegQueryValueEx(parmKey, "daemonPerformanceTuningInterval", NULL, NULL,
341                             (BYTE *) &dummy, &dummyLen);
342     dummyLen = sizeof(DWORD);
343     code = RegQueryValueEx(parmKey, "daemonRankServerInterval", NULL, NULL,
344                             (BYTE *) &dummy, &dummyLen);
345     if (code == ERROR_SUCCESS && dummy)
346         cm_daemonRankServerInterval = dummy;
347     afsi_log("daemonRankServerInterval is %d", cm_daemonRankServerInterval);
348
349     if (code == ERROR_SUCCESS)
350         cm_daemonPerformanceTuningInterval = dummy;
351     afsi_log("daemonPerformanceTuningInterval is %d", cm_daemonPerformanceTuningInterval);
352     
353     RegCloseKey(parmKey);
354
355     if (cm_daemonPerformanceTuningInterval)
356         cm_PerformanceTuningInit();
357 }
358
359 /* periodic check daemon */
360 void cm_Daemon(long parm)
361 {
362     time_t now;
363     time_t lastLockCheck;
364     time_t lastVolCheck;
365     time_t lastCBExpirationCheck;
366     time_t lastVolCBRenewalCheck;
367     time_t lastDownServerCheck;
368     time_t lastUpServerCheck;
369     time_t lastTokenCacheCheck;
370     time_t lastBusyVolCheck;
371     time_t lastPerformanceCheck;
372     time_t lastServerRankCheck;
373     char thostName[200];
374     unsigned long code;
375     struct hostent *thp;
376     HMODULE hHookDll;
377     char * name = "cm_Daemon_ShutdownEvent";
378     int configureFirewall = IsWindowsFirewallPresent();
379     int bAddrChangeCheck = 0;
380
381     cm_Daemon_ShutdownEvent = thrd_CreateEvent(NULL, FALSE, FALSE, name);
382     if ( GetLastError() == ERROR_ALREADY_EXISTS )
383         afsi_log("Event Object Already Exists: %s", name);
384
385     if (!configureFirewall) {
386         afsi_log("No Windows Firewall detected");
387     }
388
389     /* ping all file servers, up or down, with unauthenticated connection,
390      * to find out whether we have all our callbacks from the server still.
391      * Also, ping down VLDBs.
392      */
393     /*
394      * Seed the random number generator with our own address, so that
395      * clients starting at the same time don't all do vol checks at the
396      * same time.
397      */
398     gethostname(thostName, sizeof(thostName));
399     thp = gethostbyname(thostName);
400     if (thp == NULL)    /* In djgpp, gethostname returns the netbios
401                            name of the machine.  gethostbyname will fail
402                            looking this up if it differs from DNS name. */
403         code = 0;
404     else
405         memcpy(&code, thp->h_addr_list[0], 4);
406     
407     srand(ntohl(code));
408
409     cm_DaemonCheckInit();
410
411     now = osi_Time();
412     lastVolCheck = now - cm_daemonCheckVolInterval/2 + (rand() % cm_daemonCheckVolInterval);
413     lastCBExpirationCheck = now - cm_daemonCheckCBInterval/2 + (rand() % cm_daemonCheckCBInterval);
414     if (cm_daemonCheckVolCBInterval)
415         lastVolCBRenewalCheck = now - cm_daemonCheckVolCBInterval/2 + (rand() % cm_daemonCheckVolCBInterval);
416     lastLockCheck = now - cm_daemonCheckLockInterval/2 + (rand() % cm_daemonCheckLockInterval);
417     lastDownServerCheck = now - cm_daemonCheckDownInterval/2 + (rand() % cm_daemonCheckDownInterval);
418     lastUpServerCheck = now - cm_daemonCheckUpInterval/2 + (rand() % cm_daemonCheckUpInterval);
419     lastTokenCacheCheck = now - cm_daemonTokenCheckInterval/2 + (rand() % cm_daemonTokenCheckInterval);
420     lastBusyVolCheck = now - cm_daemonCheckOfflineVolInterval/2 * (rand() % cm_daemonCheckOfflineVolInterval);
421     if (cm_daemonPerformanceTuningInterval)
422         lastPerformanceCheck = now - cm_daemonPerformanceTuningInterval/2 * (rand() % cm_daemonPerformanceTuningInterval);
423     lastServerRankCheck = now - cm_daemonRankServerInterval/2 * (rand() % cm_daemonRankServerInterval);
424
425     while (daemon_ShutdownFlag == 0) {
426         if (powerStateSuspended) {
427             Sleep(1000);
428             continue;
429         }
430         /* check to see if the listener threads halted due to network 
431          * disconnect or other issues.  If so, attempt to restart them.
432          */
433         smb_RestartListeners(0);
434
435         if (daemon_ShutdownFlag == 1)
436             break;
437
438         if (configureFirewall) {
439             /* Open Microsoft Firewall to allow in port 7001 */
440             switch (icf_CheckAndAddAFSPorts(AFS_PORTSET_CLIENT)) {
441             case 0:
442                 afsi_log("Windows Firewall Configuration succeeded");
443                 configureFirewall = 0;
444                 break;
445             case 1:
446                 afsi_log("Invalid Windows Firewall Port Set");
447                 break;
448             case 2:
449                 afsi_log("Unable to open Windows Firewall Profile");
450                 break;
451             case 3:
452                 afsi_log("Unable to create/modify Windows Firewall Port entries");
453                 break;
454             default:
455                 afsi_log("Unknown Windows Firewall Configuration error");
456             }
457         }
458
459         /* find out what time it is */
460         now = osi_Time();
461
462         /* Determine whether an address change took place that we need to respond to */
463         if (bAddrChangeCheck)
464             bAddrChangeCheck = 0;
465
466         if (lastIPAddrChange != 0 && lastIPAddrChange + 2500 < now) {
467             bAddrChangeCheck = 1;
468             lastIPAddrChange = 0;
469         }
470
471         /* check down servers */
472         if ((bAddrChangeCheck || now > lastDownServerCheck + cm_daemonCheckDownInterval) &&
473             daemon_ShutdownFlag == 0 &&
474             powerStateSuspended == 0) {
475             lastDownServerCheck = now;
476             osi_Log0(afsd_logp, "cm_Daemon CheckDownServers");
477             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, NULL);
478             if (daemon_ShutdownFlag == 1)
479                 break;
480             now = osi_Time();
481         }
482
483         if (bAddrChangeCheck &&
484             daemon_ShutdownFlag == 0 &&
485             powerStateSuspended == 0)
486             cm_ForceNewConnectionsAllServers();
487
488         /* check up servers */
489         if ((bAddrChangeCheck || now > lastUpServerCheck + cm_daemonCheckUpInterval) &&
490             daemon_ShutdownFlag == 0 &&
491             powerStateSuspended == 0) {
492             lastUpServerCheck = now;
493             osi_Log0(afsd_logp, "cm_Daemon CheckUpServers");
494             cm_CheckServers(CM_FLAG_CHECKUPSERVERS, NULL);
495             if (daemon_ShutdownFlag == 1)
496                 break;
497             now = osi_Time();
498         }
499
500         if (bAddrChangeCheck &&
501             daemon_ShutdownFlag == 0 &&
502             powerStateSuspended == 0) {
503             smb_CheckVCs();
504             cm_VolStatus_Network_Addr_Change();
505         }
506
507         if (now > lastVolCheck + cm_daemonCheckVolInterval &&
508             daemon_ShutdownFlag == 0 &&
509             powerStateSuspended == 0) {
510             lastVolCheck = now;
511             cm_RefreshVolumes();
512             if (daemon_ShutdownFlag == 1)
513                 break;
514             now = osi_Time();
515         }
516
517         /* Rank all up servers */
518         if ((now > lastServerRankCheck + cm_daemonRankServerInterval) &&
519             daemon_ShutdownFlag == 0 &&
520             powerStateSuspended == 0) {
521             lastServerRankCheck = now;
522             osi_Log0(afsd_logp, "cm_Daemon RankServer");
523             cm_RankUpServers();
524             if(daemon_ShutdownFlag == 1)
525                 break;
526             now = osi_Time();
527         }
528
529         if (cm_daemonCheckVolCBInterval && 
530             now > lastVolCBRenewalCheck + cm_daemonCheckVolCBInterval &&
531             daemon_ShutdownFlag == 0 &&
532             powerStateSuspended == 0) {
533             lastVolCBRenewalCheck = now;
534             cm_VolumeRenewROCallbacks();
535             if (daemon_ShutdownFlag == 1)
536                 break;
537             now = osi_Time();
538         }
539
540         if ((bAddrChangeCheck || now > lastBusyVolCheck + cm_daemonCheckOfflineVolInterval) &&
541             daemon_ShutdownFlag == 0 &&
542             powerStateSuspended == 0) {
543             lastVolCheck = now;
544             cm_CheckOfflineVolumes();
545             if (daemon_ShutdownFlag == 1)
546                 break;
547             now = osi_Time();
548         }
549
550         if (now > lastCBExpirationCheck + cm_daemonCheckCBInterval &&
551             daemon_ShutdownFlag == 0 &&
552             powerStateSuspended == 0) {
553             lastCBExpirationCheck = now;
554             cm_CheckCBExpiration();
555             if (daemon_ShutdownFlag == 1)
556                 break;
557             now = osi_Time();
558         }
559
560         if (now > lastLockCheck + cm_daemonCheckLockInterval &&
561             daemon_ShutdownFlag == 0 &&
562             powerStateSuspended == 0) {
563             lastLockCheck = now;
564             cm_CheckLocks();
565             if (daemon_ShutdownFlag == 1)
566                 break;
567             now = osi_Time();
568         }
569
570         if (now > lastTokenCacheCheck + cm_daemonTokenCheckInterval &&
571             daemon_ShutdownFlag == 0 &&
572             powerStateSuspended == 0) {
573             lastTokenCacheCheck = now;
574             cm_CheckTokenCache(now);
575             if (daemon_ShutdownFlag == 1)
576                 break;
577             now = osi_Time();
578         }
579
580         /* allow an exit to be called prior to stopping the service */
581         hHookDll = cm_LoadAfsdHookLib();
582         if (hHookDll)
583         {
584             BOOL hookRc = TRUE;
585             AfsdDaemonHook daemonHook = ( AfsdDaemonHook ) GetProcAddress(hHookDll, AFSD_DAEMON_HOOK);
586             if (daemonHook)
587             {
588                 hookRc = daemonHook();
589             }
590             FreeLibrary(hHookDll);
591             hHookDll = NULL;
592
593             if (hookRc == FALSE)
594             {
595                 SetEvent(WaitToTerminate);
596             }
597
598             if (daemon_ShutdownFlag == 1) {
599                 break;
600             }
601             now = osi_Time();
602         }
603
604         if (cm_daemonPerformanceTuningInterval &&
605             now > lastPerformanceCheck + cm_daemonPerformanceTuningInterval &&
606             daemon_ShutdownFlag == 0 &&
607             powerStateSuspended == 0) {
608             lastPerformanceCheck = now;
609             cm_PerformanceTuningCheck();
610             if (daemon_ShutdownFlag == 1)
611                 break;
612             now = osi_Time();
613         }
614         
615         thrd_Sleep(10000);              /* sleep 10 seconds */
616     }
617     thrd_SetEvent(cm_Daemon_ShutdownEvent);
618 }       
619
620 void cm_DaemonShutdown(void)
621 {
622     int i;
623     DWORD code;
624
625     daemon_ShutdownFlag = 1;
626     osi_Wakeup((LONG_PTR) &cm_bkgListp);
627
628     /* wait for shutdown */
629     if (cm_Daemon_ShutdownEvent)
630         code = thrd_WaitForSingleObject_Event(cm_Daemon_ShutdownEvent, INFINITE); 
631
632     for ( i=0; i<cm_nDaemons; i++) {
633         if (cm_BkgDaemon_ShutdownEvent[i])
634             code = thrd_WaitForSingleObject_Event(cm_BkgDaemon_ShutdownEvent[i], INFINITE);
635     }
636
637     if (cm_IPAddrDaemon_ShutdownEvent)
638         code = thrd_WaitForSingleObject_Event(cm_IPAddrDaemon_ShutdownEvent, INFINITE);
639 }
640
641 void cm_InitDaemon(int nDaemons)
642 {
643     static osi_once_t once;
644     long pid;
645     thread_t phandle;
646     int i;
647
648     cm_nDaemons = (nDaemons > CM_MAX_DAEMONS) ? CM_MAX_DAEMONS : nDaemons;
649     
650     if (osi_Once(&once)) {
651         lock_InitializeRWLock(&cm_daemonLock, "cm_daemonLock", 
652                                LOCK_HIERARCHY_DAEMON_GLOBAL);
653         osi_EndOnce(&once);
654
655         /* creating IP Address Change monitor daemon */
656         phandle = thrd_Create((SecurityAttrib) 0, 0,
657                                (ThreadFunc) cm_IpAddrDaemon, 0, 0, &pid, "cm_IpAddrDaemon");
658         osi_assertx(phandle != NULL, "cm_IpAddrDaemon thread creation failure");
659         thrd_CloseHandle(phandle);
660
661         /* creating pinging daemon */
662         phandle = thrd_Create((SecurityAttrib) 0, 0,
663                                (ThreadFunc) cm_Daemon, 0, 0, &pid, "cm_Daemon");
664         osi_assertx(phandle != NULL, "cm_Daemon thread creation failure");
665         thrd_CloseHandle(phandle);
666
667         for(i=0; i < cm_nDaemons; i++) {
668             phandle = thrd_Create((SecurityAttrib) 0, 0,
669                                    (ThreadFunc) cm_BkgDaemon, (LPVOID)i, 0, &pid,
670                                    "cm_BkgDaemon");
671             osi_assertx(phandle != NULL, "cm_BkgDaemon thread creation failure");
672             thrd_CloseHandle(phandle);
673         }
674     }
675 }