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