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