Windows: prototype cm_PerformanceTuningInit()
[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     if (cm_freelanceEnabled && cm_freelanceImportCellServDB)
390         cm_FreelanceImportCellServDB();
391
392     /* ping all file servers, up or down, with unauthenticated connection,
393      * to find out whether we have all our callbacks from the server still.
394      * Also, ping down VLDBs.
395      */
396     /*
397      * Seed the random number generator with our own address, so that
398      * clients starting at the same time don't all do vol checks at the
399      * same time.
400      */
401     gethostname(thostName, sizeof(thostName));
402     thp = gethostbyname(thostName);
403     if (thp == NULL)    /* In djgpp, gethostname returns the netbios
404                            name of the machine.  gethostbyname will fail
405                            looking this up if it differs from DNS name. */
406         code = 0;
407     else
408         memcpy(&code, thp->h_addr_list[0], 4);
409     
410     srand(ntohl(code));
411
412     cm_DaemonCheckInit();
413
414     now = osi_Time();
415     lastVolCheck = now - cm_daemonCheckVolInterval/2 + (rand() % cm_daemonCheckVolInterval);
416     lastCBExpirationCheck = now - cm_daemonCheckCBInterval/2 + (rand() % cm_daemonCheckCBInterval);
417     if (cm_daemonCheckVolCBInterval)
418         lastVolCBRenewalCheck = now - cm_daemonCheckVolCBInterval/2 + (rand() % cm_daemonCheckVolCBInterval);
419     lastLockCheck = now - cm_daemonCheckLockInterval/2 + (rand() % cm_daemonCheckLockInterval);
420     lastDownServerCheck = now - cm_daemonCheckDownInterval/2 + (rand() % cm_daemonCheckDownInterval);
421     lastUpServerCheck = now - cm_daemonCheckUpInterval/2 + (rand() % cm_daemonCheckUpInterval);
422     lastTokenCacheCheck = now - cm_daemonTokenCheckInterval/2 + (rand() % cm_daemonTokenCheckInterval);
423     lastBusyVolCheck = now - cm_daemonCheckOfflineVolInterval/2 * (rand() % cm_daemonCheckOfflineVolInterval);
424     if (cm_daemonPerformanceTuningInterval)
425         lastPerformanceCheck = now - cm_daemonPerformanceTuningInterval/2 * (rand() % cm_daemonPerformanceTuningInterval);
426     lastServerRankCheck = now - cm_daemonRankServerInterval/2 * (rand() % cm_daemonRankServerInterval);
427
428     while (daemon_ShutdownFlag == 0) {
429         if (powerStateSuspended) {
430             Sleep(1000);
431             continue;
432         }
433         /* check to see if the listener threads halted due to network 
434          * disconnect or other issues.  If so, attempt to restart them.
435          */
436         smb_RestartListeners(0);
437
438         if (daemon_ShutdownFlag == 1)
439             break;
440
441         if (configureFirewall) {
442             /* Open Microsoft Firewall to allow in port 7001 */
443             switch (icf_CheckAndAddAFSPorts(AFS_PORTSET_CLIENT)) {
444             case 0:
445                 afsi_log("Windows Firewall Configuration succeeded");
446                 configureFirewall = 0;
447                 break;
448             case 1:
449                 afsi_log("Invalid Windows Firewall Port Set");
450                 break;
451             case 2:
452                 afsi_log("Unable to open Windows Firewall Profile");
453                 break;
454             case 3:
455                 afsi_log("Unable to create/modify Windows Firewall Port entries");
456                 break;
457             default:
458                 afsi_log("Unknown Windows Firewall Configuration error");
459             }
460         }
461
462         /* find out what time it is */
463         now = osi_Time();
464
465         /* Determine whether an address change took place that we need to respond to */
466         if (bAddrChangeCheck)
467             bAddrChangeCheck = 0;
468
469         if (lastIPAddrChange != 0 && lastIPAddrChange + 2500 < now) {
470             bAddrChangeCheck = 1;
471             lastIPAddrChange = 0;
472         }
473
474         /* check down servers */
475         if ((bAddrChangeCheck || now > lastDownServerCheck + cm_daemonCheckDownInterval) &&
476             daemon_ShutdownFlag == 0 &&
477             powerStateSuspended == 0) {
478             lastDownServerCheck = now;
479             osi_Log0(afsd_logp, "cm_Daemon CheckDownServers");
480             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, NULL);
481             if (daemon_ShutdownFlag == 1)
482                 break;
483             now = osi_Time();
484         }
485
486         if (bAddrChangeCheck &&
487             daemon_ShutdownFlag == 0 &&
488             powerStateSuspended == 0)
489             cm_ForceNewConnectionsAllServers();
490
491         /* check up servers */
492         if ((bAddrChangeCheck || now > lastUpServerCheck + cm_daemonCheckUpInterval) &&
493             daemon_ShutdownFlag == 0 &&
494             powerStateSuspended == 0) {
495             lastUpServerCheck = now;
496             osi_Log0(afsd_logp, "cm_Daemon CheckUpServers");
497             cm_CheckServers(CM_FLAG_CHECKUPSERVERS, NULL);
498             if (daemon_ShutdownFlag == 1)
499                 break;
500             now = osi_Time();
501         }
502
503         if (bAddrChangeCheck &&
504             daemon_ShutdownFlag == 0 &&
505             powerStateSuspended == 0) {
506             smb_CheckVCs();
507             cm_VolStatus_Network_Addr_Change();
508         }
509
510         /*
511          * Once every five minutes inspect the volume list and enforce
512          * the volume location expiration time.
513          */
514         if (now > lastVolCheck + 300 &&
515             daemon_ShutdownFlag == 0 &&
516             powerStateSuspended == 0) {
517             lastVolCheck = now;
518             cm_RefreshVolumes(cm_daemonCheckVolInterval);
519             if (daemon_ShutdownFlag == 1)
520                 break;
521             now = osi_Time();
522         }
523
524         /* Rank all up servers */
525         if ((now > lastServerRankCheck + cm_daemonRankServerInterval) &&
526             daemon_ShutdownFlag == 0 &&
527             powerStateSuspended == 0) {
528             lastServerRankCheck = now;
529             osi_Log0(afsd_logp, "cm_Daemon RankServer");
530             cm_RankUpServers();
531             if(daemon_ShutdownFlag == 1)
532                 break;
533             now = osi_Time();
534         }
535
536         if (cm_daemonCheckVolCBInterval && 
537             now > lastVolCBRenewalCheck + cm_daemonCheckVolCBInterval &&
538             daemon_ShutdownFlag == 0 &&
539             powerStateSuspended == 0) {
540             lastVolCBRenewalCheck = now;
541             cm_VolumeRenewROCallbacks();
542             if (daemon_ShutdownFlag == 1)
543                 break;
544             now = osi_Time();
545         }
546
547         if ((bAddrChangeCheck || now > lastBusyVolCheck + cm_daemonCheckOfflineVolInterval) &&
548             daemon_ShutdownFlag == 0 &&
549             powerStateSuspended == 0) {
550             lastVolCheck = now;
551             cm_CheckOfflineVolumes();
552             if (daemon_ShutdownFlag == 1)
553                 break;
554             now = osi_Time();
555         }
556
557         if (now > lastCBExpirationCheck + cm_daemonCheckCBInterval &&
558             daemon_ShutdownFlag == 0 &&
559             powerStateSuspended == 0) {
560             lastCBExpirationCheck = now;
561             cm_CheckCBExpiration();
562             if (daemon_ShutdownFlag == 1)
563                 break;
564             now = osi_Time();
565         }
566
567         if (now > lastLockCheck + cm_daemonCheckLockInterval &&
568             daemon_ShutdownFlag == 0 &&
569             powerStateSuspended == 0) {
570             lastLockCheck = now;
571             cm_CheckLocks();
572             if (daemon_ShutdownFlag == 1)
573                 break;
574             now = osi_Time();
575         }
576
577         if (now > lastTokenCacheCheck + cm_daemonTokenCheckInterval &&
578             daemon_ShutdownFlag == 0 &&
579             powerStateSuspended == 0) {
580             lastTokenCacheCheck = now;
581             cm_CheckTokenCache(now);
582             if (daemon_ShutdownFlag == 1)
583                 break;
584             now = osi_Time();
585         }
586
587         /* allow an exit to be called prior to stopping the service */
588         hHookDll = cm_LoadAfsdHookLib();
589         if (hHookDll)
590         {
591             BOOL hookRc = TRUE;
592             AfsdDaemonHook daemonHook = ( AfsdDaemonHook ) GetProcAddress(hHookDll, AFSD_DAEMON_HOOK);
593             if (daemonHook)
594             {
595                 hookRc = daemonHook();
596             }
597             FreeLibrary(hHookDll);
598             hHookDll = NULL;
599
600             if (hookRc == FALSE)
601             {
602                 SetEvent(WaitToTerminate);
603             }
604
605             if (daemon_ShutdownFlag == 1) {
606                 break;
607             }
608             now = osi_Time();
609         }
610
611         if (cm_daemonPerformanceTuningInterval &&
612             now > lastPerformanceCheck + cm_daemonPerformanceTuningInterval &&
613             daemon_ShutdownFlag == 0 &&
614             powerStateSuspended == 0) {
615             lastPerformanceCheck = now;
616             cm_PerformanceTuningCheck();
617             if (daemon_ShutdownFlag == 1)
618                 break;
619             now = osi_Time();
620         }
621         
622         thrd_Sleep(10000);              /* sleep 10 seconds */
623     }
624     thrd_SetEvent(cm_Daemon_ShutdownEvent);
625 }       
626
627 void cm_DaemonShutdown(void)
628 {
629     int i;
630     DWORD code;
631
632     daemon_ShutdownFlag = 1;
633     osi_Wakeup((LONG_PTR) &cm_bkgListp);
634
635     /* wait for shutdown */
636     if (cm_Daemon_ShutdownEvent)
637         code = thrd_WaitForSingleObject_Event(cm_Daemon_ShutdownEvent, INFINITE); 
638
639     for ( i=0; i<cm_nDaemons; i++) {
640         if (cm_BkgDaemon_ShutdownEvent[i])
641             code = thrd_WaitForSingleObject_Event(cm_BkgDaemon_ShutdownEvent[i], INFINITE);
642     }
643
644     if (cm_IPAddrDaemon_ShutdownEvent)
645         code = thrd_WaitForSingleObject_Event(cm_IPAddrDaemon_ShutdownEvent, INFINITE);
646 }
647
648 void cm_InitDaemon(int nDaemons)
649 {
650     static osi_once_t once;
651     long pid;
652     thread_t phandle;
653     int i;
654
655     cm_nDaemons = (nDaemons > CM_MAX_DAEMONS) ? CM_MAX_DAEMONS : nDaemons;
656     
657     if (osi_Once(&once)) {
658         lock_InitializeRWLock(&cm_daemonLock, "cm_daemonLock", 
659                                LOCK_HIERARCHY_DAEMON_GLOBAL);
660         osi_EndOnce(&once);
661
662         /* creating IP Address Change monitor daemon */
663         phandle = thrd_Create((SecurityAttrib) 0, 0,
664                                (ThreadFunc) cm_IpAddrDaemon, 0, 0, &pid, "cm_IpAddrDaemon");
665         osi_assertx(phandle != NULL, "cm_IpAddrDaemon thread creation failure");
666         thrd_CloseHandle(phandle);
667
668         /* creating pinging daemon */
669         phandle = thrd_Create((SecurityAttrib) 0, 0,
670                                (ThreadFunc) cm_Daemon, 0, 0, &pid, "cm_Daemon");
671         osi_assertx(phandle != NULL, "cm_Daemon thread creation failure");
672         thrd_CloseHandle(phandle);
673
674         for(i=0; i < cm_nDaemons; i++) {
675             phandle = thrd_Create((SecurityAttrib) 0, 0,
676                                    (ThreadFunc) cm_BkgDaemon, (LPVOID)i, 0, &pid,
677                                    "cm_BkgDaemon");
678             osi_assertx(phandle != NULL, "cm_BkgDaemon thread creation failure");
679             thrd_CloseHandle(phandle);
680         }
681     }
682 }