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