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