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