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