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