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