627f9a08ce30d9bcdc1f0ac303aac2d317486229
[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             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     lastBusyVolCheck = now - cm_daemonCheckOfflineVolInterval/2 * (rand() % cm_daemonCheckOfflineVolInterval);
471     if (cm_daemonPerformanceTuningInterval)
472         lastPerformanceCheck = now - cm_daemonPerformanceTuningInterval/2 * (rand() % cm_daemonPerformanceTuningInterval);
473     lastServerRankCheck = now - cm_daemonRankServerInterval/2 * (rand() % cm_daemonRankServerInterval);
474
475     while (daemon_ShutdownFlag == 0) {
476         if (powerStateSuspended) {
477             Sleep(1000);
478             continue;
479         }
480         /* check to see if the listener threads halted due to network
481          * disconnect or other issues.  If so, attempt to restart them.
482          */
483         smb_RestartListeners(0);
484
485         if (daemon_ShutdownFlag == 1)
486             break;
487
488         if (configureFirewall) {
489             /* Open Microsoft Firewall to allow in port 7001 */
490             switch (icf_CheckAndAddAFSPorts(AFS_PORTSET_CLIENT)) {
491             case 0:
492                 afsi_log("Windows Firewall Configuration succeeded");
493                 configureFirewall = 0;
494                 break;
495             case 1:
496                 afsi_log("Invalid Windows Firewall Port Set");
497                 break;
498             case 2:
499                 afsi_log("Unable to open Windows Firewall Profile");
500                 break;
501             case 3:
502                 afsi_log("Unable to create/modify Windows Firewall Port entries");
503                 break;
504             default:
505                 afsi_log("Unknown Windows Firewall Configuration error");
506             }
507         }
508
509         /* find out what time it is */
510         now = osi_Time();
511
512         /* Determine whether an address change took place that we need to respond to */
513         if (bAddrChangeCheck)
514             bAddrChangeCheck = 0;
515
516         if (lastIPAddrChange != 0 && lastIPAddrChange + 2500 < now) {
517             bAddrChangeCheck = 1;
518             lastIPAddrChange = 0;
519         }
520
521         /* check down servers */
522         if ((bAddrChangeCheck || now > lastDownServerCheck + cm_daemonCheckDownInterval) &&
523             daemon_ShutdownFlag == 0 &&
524             powerStateSuspended == 0) {
525             lastDownServerCheck = now;
526             osi_Log0(afsd_logp, "cm_Daemon CheckDownServers");
527             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, NULL);
528             if (daemon_ShutdownFlag == 1)
529                 break;
530             now = osi_Time();
531         }
532
533         if (bAddrChangeCheck &&
534             daemon_ShutdownFlag == 0 &&
535             powerStateSuspended == 0) {
536             cm_ForceNewConnectionsAllServers();
537         }
538
539         /* check up servers */
540         if ((bAddrChangeCheck || now > lastUpServerCheck + cm_daemonCheckUpInterval) &&
541             daemon_ShutdownFlag == 0 &&
542             powerStateSuspended == 0) {
543             lastUpServerCheck = now;
544             osi_Log0(afsd_logp, "cm_Daemon CheckUpServers");
545             cm_CheckServers(CM_FLAG_CHECKUPSERVERS, NULL);
546             if (daemon_ShutdownFlag == 1)
547                 break;
548             now = osi_Time();
549         }
550
551         if (bAddrChangeCheck &&
552             daemon_ShutdownFlag == 0 &&
553             powerStateSuspended == 0) {
554             smb_CheckVCs();
555             cm_VolStatus_Network_Addr_Change();
556         }
557
558         /*
559          * Once every five minutes inspect the volume list and enforce
560          * the volume location expiration time.
561          */
562         if (now > lastVolCheck + 300 &&
563             daemon_ShutdownFlag == 0 &&
564             powerStateSuspended == 0) {
565             lastVolCheck = now;
566             cm_RefreshVolumes(cm_daemonCheckVolInterval);
567             if (daemon_ShutdownFlag == 1)
568                 break;
569             now = osi_Time();
570         }
571
572         /* Rank all up servers */
573         if ((now > lastServerRankCheck + cm_daemonRankServerInterval) &&
574             daemon_ShutdownFlag == 0 &&
575             powerStateSuspended == 0) {
576             lastServerRankCheck = now;
577             osi_Log0(afsd_logp, "cm_Daemon RankServer");
578             cm_RankUpServers();
579             if(daemon_ShutdownFlag == 1)
580                 break;
581             now = osi_Time();
582         }
583
584         if (cm_daemonCheckVolCBInterval &&
585             now > lastVolCBRenewalCheck + cm_daemonCheckVolCBInterval &&
586             daemon_ShutdownFlag == 0 &&
587             powerStateSuspended == 0) {
588             lastVolCBRenewalCheck = now;
589             cm_VolumeRenewROCallbacks();
590             if (daemon_ShutdownFlag == 1)
591                 break;
592             now = osi_Time();
593         }
594
595         if ((bAddrChangeCheck || now > lastBusyVolCheck + cm_daemonCheckOfflineVolInterval) &&
596             daemon_ShutdownFlag == 0 &&
597             powerStateSuspended == 0) {
598             lastBusyVolCheck = now;
599             cm_CheckOfflineVolumes();
600             if (daemon_ShutdownFlag == 1)
601                 break;
602             now = osi_Time();
603         }
604
605         if (now > lastCBExpirationCheck + cm_daemonCheckCBInterval &&
606             daemon_ShutdownFlag == 0 &&
607             powerStateSuspended == 0) {
608             lastCBExpirationCheck = now;
609             cm_CheckCBExpiration();
610             if (daemon_ShutdownFlag == 1)
611                 break;
612             now = osi_Time();
613         }
614
615         if (now > lastTokenCacheCheck + cm_daemonTokenCheckInterval &&
616             daemon_ShutdownFlag == 0 &&
617             powerStateSuspended == 0) {
618             lastTokenCacheCheck = now;
619             cm_CheckTokenCache(now);
620             if (daemon_ShutdownFlag == 1)
621                 break;
622             now = osi_Time();
623         }
624
625         /* allow an exit to be called prior to stopping the service */
626         hHookDll = cm_LoadAfsdHookLib();
627         if (hHookDll)
628         {
629             BOOL hookRc = TRUE;
630             AfsdDaemonHook daemonHook = ( AfsdDaemonHook ) GetProcAddress(hHookDll, AFSD_DAEMON_HOOK);
631             if (daemonHook)
632             {
633                 hookRc = daemonHook();
634             }
635             FreeLibrary(hHookDll);
636             hHookDll = NULL;
637
638             if (hookRc == FALSE)
639             {
640                 SetEvent(WaitToTerminate);
641             }
642
643             if (daemon_ShutdownFlag == 1) {
644                 break;
645             }
646             now = osi_Time();
647         }
648
649         if (cm_daemonPerformanceTuningInterval &&
650             now > lastPerformanceCheck + cm_daemonPerformanceTuningInterval &&
651             daemon_ShutdownFlag == 0 &&
652             powerStateSuspended == 0) {
653             lastPerformanceCheck = now;
654             cm_PerformanceTuningCheck();
655             if (daemon_ShutdownFlag == 1)
656                 break;
657             now = osi_Time();
658         }
659
660         /*
661          * sleep .5 seconds.  if the thread blocks for a long time
662          * we risk not being able to close the cache before Windows
663          * kills our process during system shutdown.
664          */
665         thrd_Sleep(500);
666     }
667
668     thrd_SetEvent(cm_Daemon_ShutdownEvent);
669 }
670
671 void cm_DaemonShutdown(void)
672 {
673     int i;
674     DWORD code;
675
676     daemon_ShutdownFlag = 1;
677     osi_Wakeup((LONG_PTR) &cm_bkgListp);
678
679     /* wait for shutdown */
680     for ( i=0; i<cm_nDaemons; i++) {
681         if (cm_BkgDaemon_ShutdownEvent[i])
682             code = thrd_WaitForSingleObject_Event(cm_BkgDaemon_ShutdownEvent[i], INFINITE);
683     }
684
685     if (cm_Daemon_ShutdownEvent)
686         code = thrd_WaitForSingleObject_Event(cm_Daemon_ShutdownEvent, INFINITE);
687
688     if (cm_LockDaemon_ShutdownEvent)
689         code = thrd_WaitForSingleObject_Event(cm_LockDaemon_ShutdownEvent, INFINITE);
690
691 #if 0
692     /*
693      * Do not waste precious time waiting for the ipaddr daemon to shutdown.
694      * When it does it means we have lost our network connection and we need
695      * it during cache shutdown in order to notify the file servers that this
696      * client is giving up all callbacks.
697      */
698     if (cm_IPAddrDaemon_ShutdownEvent)
699         code = thrd_WaitForSingleObject_Event(cm_IPAddrDaemon_ShutdownEvent, INFINITE);
700 #endif
701 }
702
703 void cm_InitDaemon(int nDaemons)
704 {
705     static osi_once_t once;
706     long pid;
707     thread_t phandle;
708     int i;
709
710     cm_nDaemons = (nDaemons > CM_MAX_DAEMONS) ? CM_MAX_DAEMONS : nDaemons;
711
712     if (osi_Once(&once)) {
713         lock_InitializeRWLock(&cm_daemonLock, "cm_daemonLock",
714                                LOCK_HIERARCHY_DAEMON_GLOBAL);
715         osi_EndOnce(&once);
716
717         /* creating IP Address Change monitor daemon */
718         phandle = thrd_Create((SecurityAttrib) 0, 0,
719                                (ThreadFunc) cm_IpAddrDaemon, 0, 0, &pid, "cm_IpAddrDaemon");
720         osi_assertx(phandle != NULL, "cm_IpAddrDaemon thread creation failure");
721         thrd_CloseHandle(phandle);
722
723         /* creating pinging daemon */
724         phandle = thrd_Create((SecurityAttrib) 0, 0,
725                                (ThreadFunc) cm_Daemon, 0, 0, &pid, "cm_Daemon");
726         osi_assertx(phandle != NULL, "cm_Daemon thread creation failure");
727         thrd_CloseHandle(phandle);
728
729         phandle = thrd_Create((SecurityAttrib) 0, 0,
730                                (ThreadFunc) cm_LockDaemon, 0, 0, &pid, "cm_LockDaemon");
731         osi_assertx(phandle != NULL, "cm_LockDaemon thread creation failure");
732         thrd_CloseHandle(phandle);
733
734         for(i=0; i < cm_nDaemons; i++) {
735             phandle = thrd_Create((SecurityAttrib) 0, 0,
736                                    (ThreadFunc) cm_BkgDaemon, (LPVOID)(LONG_PTR)i, 0, &pid,
737                                    "cm_BkgDaemon");
738             osi_assertx(phandle != NULL, "cm_BkgDaemon thread creation failure");
739             thrd_CloseHandle(phandle);
740         }
741     }
742 }