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