2cf0a171b55a23ecc10ab23030d4c77faf132b00
[openafs.git] / src / WINNT / afsd / cm_callback.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 <afs/param.h>
11 #include <afs/afs_args.h>
12 #include <afs/stds.h>
13
14 #include <windows.h>
15 #include <winsock2.h>
16 #include <malloc.h>
17 #include <string.h>
18 #include <stdlib.h>
19
20 #include "afsd.h"
21 #include <osi.h>
22 #include <rx_pthread.h>
23
24 #include <WINNT/syscfg.h>
25 #include <WINNT/afsreg.h>
26 #include <../afsrdr/kif.h>
27
28 /*extern void afsi_log(char *pattern, ...);*/
29
30 /* read/write lock for all global storage in this module */
31 osi_rwlock_t cm_callbackLock;
32
33 #ifdef AFS_FREELANCE_CLIENT
34 extern osi_mutex_t cm_Freelance_Lock;
35 #endif
36
37 /* count of # of callback breaking messages received by this CM so far.  We use
38  * this count in determining whether there have been any callback breaks that
39  * apply to a call that returned a new callback.  If the counter doesn't
40  * increase during a call, then we know that no callbacks were broken during
41  * that call, and thus that the callback that was just returned is still valid.
42  */
43 long cm_callbackCount;
44
45 /* count of number of RPCs potentially returning a callback executing now.
46  * When this counter hits zero, we can clear out the racing revokes list, since
47  * at that time, we know that none of the just-executed callback revokes will
48  * apply to any future call that returns a callback (since the latter hasn't
49  * even started execution yet).
50  */
51 long cm_activeCallbackGrantingCalls;
52
53 /* list of callbacks that have been broken recently.  If a call returning a
54  * callback is executing and a callback revoke runs immediately after it at the
55  * server, the revoke may end up being processed before the response to the
56  * original callback granting call.  We detect this by keeping a list of
57  * callback revokes that have been received since we *started* the callback
58  * granting call, and discarding any callbacks received for the same file ID,
59  * even if the callback revoke was received before the callback grant.
60  */
61 cm_racingRevokes_t *cm_racingRevokesp;
62
63 /* record a (potentially) racing revoke for this file ID; null means for all
64  * file IDs, and is used by InitCallBackState.
65  *
66  * The cancelFlags describe whether we're just discarding callbacks for the same
67  * file ID, the same volume, or all from the same server.
68  *
69  * Called with no locks held.
70  */
71 void cm_RecordRacingRevoke(cm_fid_t *fidp, long cancelFlags)
72 {
73     cm_racingRevokes_t *rp;
74
75     lock_ObtainWrite(&cm_callbackLock);
76
77     osi_Log3(afsd_logp, "RecordRacingRevoke Volume %d Flags %lX activeCalls %d",
78                 fidp ? fidp->volume : 0, cancelFlags, cm_activeCallbackGrantingCalls);
79
80     if (cm_activeCallbackGrantingCalls > 0) {
81         rp = malloc(sizeof(*rp));
82         memset(rp, 0, sizeof(*rp));
83         osi_QAdd((osi_queue_t **) &cm_racingRevokesp, &rp->q);
84         rp->flags |= (cancelFlags & CM_RACINGFLAG_ALL);
85         if (fidp) rp->fid = *fidp;
86         rp->callbackCount = ++cm_callbackCount;
87     }
88     lock_ReleaseWrite(&cm_callbackLock);
89 }
90
91 /*
92  * When we lose a callback, may have to send change notification replies.
93  * Do not call with a lock on the scp.
94  */
95 void cm_CallbackNotifyChange(cm_scache_t *scp)
96 {
97     DWORD dwDelay = 0;
98     HKEY  hKey;
99     DWORD dummyLen;
100
101     /* why does this have to query the registry each time? */
102         if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
103                       AFSREG_CLT_OPENAFS_SUBKEY,
104                       0,
105                       KEY_READ|KEY_QUERY_VALUE,
106                       &hKey) == ERROR_SUCCESS) {
107
108         dummyLen = sizeof(DWORD);
109         RegQueryValueEx(hKey, "CallBack Notify Change Delay", NULL, NULL,
110                         (BYTE *) &dwDelay, &dummyLen);
111         RegCloseKey(hKey);
112     }
113
114     if (dwDelay > 5000)    /* do not allow a delay of more then 5 seconds */
115         dwDelay = 5000;   
116
117     osi_Log3(afsd_logp, "CallbackNotifyChange FileType %d Flags %lX Delay %dms",
118               scp->fileType, scp->flags, dwDelay);
119
120     if (dwDelay)
121         Sleep(dwDelay);
122
123     /* for directories, this sends a change notification on the dir itself */
124     if (scp->fileType == CM_SCACHETYPE_DIRECTORY) {
125 #ifndef AFSIFS
126         if (scp->flags & CM_SCACHEFLAG_ANYWATCH)
127             smb_NotifyChange(0,
128                              FILE_NOTIFY_GENERIC_DIRECTORY_FILTER,
129                              scp, NULL, NULL, TRUE);
130 #else
131         dc_break_callback(FID_HASH_FN(&scp->fid));
132 #endif
133     } else {
134         /* and for files, this sends a change notification on the file's parent dir */
135         cm_fid_t tfid;
136         cm_scache_t *dscp;
137
138         tfid.cell = scp->fid.cell;
139         tfid.volume = scp->fid.volume;
140         tfid.vnode = scp->parentVnode;
141         tfid.unique = scp->parentUnique;
142         dscp = cm_FindSCache(&tfid);
143 #ifndef AFSIFS
144         if ( dscp &&
145              dscp->flags & CM_SCACHEFLAG_ANYWATCH )
146             smb_NotifyChange( 0,
147                               FILE_NOTIFY_GENERIC_FILE_FILTER,
148                               dscp,   NULL, NULL, TRUE);
149 #else
150         if (dscp)
151             dc_break_callback(FID_HASH_FN(&dscp->fid));
152 #endif
153         if (dscp) 
154             cm_ReleaseSCache(dscp);
155     }
156 }
157
158 /* called with no locks held for every file ID that is revoked directly by
159  * a callback revoke call.  Does not have to handle volume callback breaks,
160  * since those have already been split out.
161  *
162  * The callp parameter is currently unused.
163  */
164 void cm_RevokeCallback(struct rx_call *callp, AFSFid *fidp)
165 {
166     cm_fid_t tfid;
167     cm_scache_t *scp;
168     long hash;
169         
170     /* don't bother setting cell, since we won't be checking it (to aid
171      * in working with multi-homed servers: we don't know the cell if we
172      * don't recognize the IP address).
173      */
174     tfid.cell = 0;
175     tfid.volume = fidp->Volume;
176     tfid.vnode = fidp->Vnode;
177     tfid.unique = fidp->Unique;
178     hash = CM_SCACHE_HASH(&tfid);
179
180     osi_Log3(afsd_logp, "RevokeCallback vol %u vn %u uniq %u",
181              fidp->Volume, fidp->Vnode, fidp->Unique);
182         
183     /* do this first, so that if we're executing a callback granting call
184      * at this moment, we kill it before it can be merged in.  Otherwise,
185      * it could complete while we're doing the scan below, and get missed
186      * by both the scan and by this code.
187      */
188     cm_RecordRacingRevoke(&tfid, 0);
189
190     lock_ObtainWrite(&cm_scacheLock);
191     /* do all in the hash bucket, since we don't know how many we'll find with
192      * varying cells.
193      */
194     for (scp = cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
195         if (scp->fid.volume == tfid.volume &&
196              scp->fid.vnode == tfid.vnode &&
197              scp->fid.unique == tfid.unique &&
198              scp->cbExpires > 0 && 
199              scp->cbServerp != NULL)
200         {
201             cm_HoldSCacheNoLock(scp);
202             lock_ReleaseWrite(&cm_scacheLock);
203             osi_Log4(afsd_logp, "RevokeCallback Discarding SCache scp 0x%p vol %u vn %u uniq %u", 
204                      scp, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
205             lock_ObtainMutex(&scp->mx);
206             cm_DiscardSCache(scp);
207             lock_ReleaseMutex(&scp->mx);
208             cm_CallbackNotifyChange(scp);
209             lock_ObtainWrite(&cm_scacheLock);
210             cm_ReleaseSCacheNoLock(scp);
211         }
212     }
213     lock_ReleaseWrite(&cm_scacheLock);
214
215     osi_Log3(afsd_logp, "RevokeCallback Complete vol %u vn %u uniq %u",
216              fidp->Volume, fidp->Vnode, fidp->Unique);
217 }
218
219 /* called to revoke a volume callback, which is typically issued when a volume
220  * is moved from one server to another.
221  *
222  * Called with no locks held.
223  */
224 void cm_RevokeVolumeCallback(struct rx_call *callp, AFSFid *fidp)
225 {
226     long hash;
227     cm_scache_t *scp;
228     cm_fid_t tfid;
229
230     osi_Log1(afsd_logp, "RevokeVolumeCallback vol %d", fidp->Volume);
231
232     /* do this first, so that if we're executing a callback granting call
233      * at this moment, we kill it before it can be merged in.  Otherwise,
234      * it could complete while we're doing the scan below, and get missed
235      * by both the scan and by this code.
236      */
237     tfid.cell = tfid.vnode = tfid.unique = 0;
238     tfid.volume = fidp->Volume;
239     cm_RecordRacingRevoke(&tfid, CM_RACINGFLAG_CANCELVOL);
240
241
242     lock_ObtainWrite(&cm_scacheLock);
243     for (hash = 0; hash < cm_data.hashTableSize; hash++) {
244         for(scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
245             if (scp->fid.volume == fidp->Volume &&
246                  scp->cbExpires > 0 &&
247                  scp->cbServerp != NULL) {
248                 cm_HoldSCacheNoLock(scp);
249                 lock_ReleaseWrite(&cm_scacheLock);
250                 lock_ObtainMutex(&scp->mx);
251                 osi_Log4(afsd_logp, "RevokeVolumeCallback Discarding SCache scp 0x%p vol %u vn %u uniq %u", 
252                           scp, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
253                 cm_DiscardSCache(scp);
254                 lock_ReleaseMutex(&scp->mx);
255                 cm_CallbackNotifyChange(scp);
256                 lock_ObtainWrite(&cm_scacheLock);
257                 cm_ReleaseSCacheNoLock(scp);
258             }
259         }       /* search one hash bucket */
260     }   /* search all hash buckets */
261
262     lock_ReleaseWrite(&cm_scacheLock);
263
264     osi_Log1(afsd_logp, "RevokeVolumeCallback Complete vol %d", fidp->Volume);
265 }
266
267 /*
268  * afs_data_pointer_to_int32() - returns least significant afs_int32 of the
269  * given data pointer, without triggering "cast truncates pointer"
270  * warnings.  We use this where we explicitly don't care whether a
271  * pointer is truncated -- it loses information where a pointer is
272  * larger than an afs_int32.
273  */
274
275 static afs_int32
276 afs_data_pointer_to_int32(const void *p)
277 {
278     union {
279         afs_int32 i32[sizeof(void *) / sizeof(afs_int32)];
280         const void *p;
281     } ip;
282
283     int i32_sub;                /* subscript of least significant afs_int32 in ip.i32[] */
284
285     /* set i32_sub */
286
287     {
288         /* used to determine the byte order of the system */
289
290         union {
291             char c[sizeof(int) / sizeof(char)];
292             int i;
293         } ci;
294
295         ci.i = 1;
296         if (ci.c[0] == 1) {
297             /* little-endian system */
298             i32_sub = 0;
299         } else {
300             /* big-endian system */
301             i32_sub = (sizeof ip.i32 / sizeof ip.i32[0]) - 1;
302         }
303     }
304
305     ip.p = p;
306     return ip.i32[i32_sub];
307 }
308 /*------------------------------------------------------------------------
309  * EXPORTED SRXAFSCB_CallBack
310  *
311  * Description:
312  *      Routine called by the server-side callback RPC interface to
313  *      implement passing in callback information.
314  *      table.
315  *
316  * Arguments:
317  *      rx_call    : Ptr to Rx call on which this request came in.
318  *      fidsArrayp : Ptr to array of fids involved.
319  *      cbsArrayp  : Ptr to matching callback info for the fids.
320  *
321  * Returns:
322  *      0 (always).
323  *
324  * Environment:
325  *      Nothing interesting.
326  *
327  * Side Effects:
328  *      As advertised.
329  *------------------------------------------------------------------------*/
330 /* handle incoming RPC callback breaking message.
331  * Called with no locks held.
332  */
333 int
334 SRXAFSCB_CallBack(struct rx_call *callp, AFSCBFids *fidsArrayp, AFSCBs *cbsArrayp)
335 {
336     int i;
337     AFSFid *tfidp;
338     struct rx_connection *connp;
339     struct rx_peer *peerp;
340     unsigned long host = 0;
341     unsigned short port = 0;
342
343     MUTEX_ENTER(&callp->lock);
344
345     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
346         host = rx_HostOf(peerp);
347         port = rx_PortOf(peerp);
348     }
349
350     osi_Log2(afsd_logp, "SRXAFSCB_CallBack from host 0x%x port %d",
351               ntohl(host),
352               ntohs(port));
353
354     for (i=0; i < (long) fidsArrayp->AFSCBFids_len; i++) {
355         tfidp = &fidsArrayp->AFSCBFids_val[i];
356                 
357         if (tfidp->Volume == 0)
358             continue;   /* means don't do anything */
359         else if (tfidp->Vnode == 0)
360             cm_RevokeVolumeCallback(callp, tfidp);
361         else
362             cm_RevokeCallback(callp, tfidp);
363     }
364
365     MUTEX_EXIT(&callp->lock);
366     return 0;
367 }
368
369 /*------------------------------------------------------------------------
370  * EXPORTED SRXAFSCB_InitCallBackState
371  *
372  * Description:
373  *      Routine called by the server-side callback RPC interface to
374  *      implement clearing all callbacks from this host.
375  *
376  * Arguments:
377  *      rx_call : Ptr to Rx call on which this request came in.
378  *
379  * Returns:
380  *      0 (always).
381  *
382  * Environment:
383  *      Nothing interesting.
384  *
385  * Side Effects:
386  *      As advertised.
387  *------------------------------------------------------------------------*/
388 /* called with no locks by RPC system when a server indicates that it has never
389  * heard from us, or for other reasons has had to discard callbacks from us
390  * without telling us, e.g. a network partition.
391  */
392 int
393 SRXAFSCB_InitCallBackState(struct rx_call *callp)
394 {
395     struct sockaddr_in taddr;
396     cm_server_t *tsp;
397     cm_scache_t *scp;
398     int hash;
399     int discarded;
400     struct rx_connection *connp;
401     struct rx_peer *peerp;
402     unsigned long host = 0;
403     unsigned short port = 0;
404
405     MUTEX_ENTER(&callp->lock);
406
407     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
408         host = rx_HostOf(peerp);
409         port = rx_PortOf(peerp);
410     }
411
412     osi_Log2(afsd_logp, "SRXAFSCB_InitCallBackState from host 0x%x port %d",
413               ntohl(host),
414               ntohs(port));
415
416     if ((rx_ConnectionOf(callp)) && (rx_PeerOf(rx_ConnectionOf(callp)))) {
417         taddr.sin_family = AF_INET;
418         taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(rx_ConnectionOf(callp)));
419
420         tsp = cm_FindServer(&taddr, CM_SERVER_FILE);
421
422         osi_Log1(afsd_logp, "Init Callback State server %x", tsp);
423         
424         /* record the callback in the racing revokes structure.  This
425          * shouldn't be necessary, since we shouldn't be making callback
426          * granting calls while we're going to get an initstate call,
427          * but there probably are some obscure races, so better safe
428          * than sorry.
429          *
430          * We do this first since we don't hold the cm_scacheLock and vnode
431          * locks over the entire callback scan operation below.  The
432          * big loop below is guaranteed to hit any callback already
433          * processed.  The call to RecordRacingRevoke is guaranteed
434          * to kill any callback that is currently being returned.
435          * Anything that sneaks past both must start
436          * after the call to RecordRacingRevoke.
437          */
438         cm_RecordRacingRevoke(NULL, CM_RACINGFLAG_CANCELALL);
439         
440         /* now search all vnodes looking for guys with this callback, if we
441          * found it, or guys with any callbacks, if we didn't find the server
442          * (that's how multihomed machines will appear and how we'll handle
443          * them, albeit a little inefficiently).  That is, we're discarding all
444          * callbacks from all hosts if we get an initstate call from an unknown
445          * host.  Since these calls are rare, and multihomed servers
446          * are "rare," hopefully this won't be a problem.
447          */
448         lock_ObtainWrite(&cm_scacheLock);
449         for (hash = 0; hash < cm_data.hashTableSize; hash++) {
450             for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
451                 cm_HoldSCacheNoLock(scp);
452                 lock_ReleaseWrite(&cm_scacheLock);
453                 lock_ObtainMutex(&scp->mx);
454                 discarded = 0;
455                 if (scp->cbExpires > 0 && scp->cbServerp != NULL) {
456                     /* we have a callback, now decide if we should clear it */
457                     if (scp->cbServerp == tsp || tsp == NULL) {
458                         osi_Log4(afsd_logp, "InitCallbackState Discarding SCache scp 0x%p vol %u vn %u uniq %u", 
459                                   scp, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
460                         cm_DiscardSCache(scp);
461                         discarded = 1;
462                     }
463                 }
464                 lock_ReleaseMutex(&scp->mx);
465                 if (discarded)
466                     cm_CallbackNotifyChange(scp);
467                 lock_ObtainWrite(&cm_scacheLock);
468                 cm_ReleaseSCacheNoLock(scp);
469             }   /* search one hash bucket */
470         }       /* search all hash buckets */
471         
472         lock_ReleaseWrite(&cm_scacheLock);
473         
474         if (tsp) {
475             /* reset the No flags on the server */
476             cm_SetServerNo64Bit(tsp, 0);
477             cm_SetServerNoInlineBulk(tsp, 0);
478
479             /* we're done with the server structure */
480             cm_PutServer(tsp);
481         }
482     }
483     MUTEX_EXIT(&callp->lock);
484     return 0;
485 }
486
487 /*------------------------------------------------------------------------
488  * EXPORTED SRXAFSCB_Probe
489  *
490  * Description:
491  *      Routine called by the server-side callback RPC interface to
492  *      implement ``probing'' the Cache Manager, just making sure it's
493  *      still there.
494  *
495  * Arguments:
496  *      rx_call : Ptr to Rx call on which this request came in.
497  *
498  * Returns:
499  *      0 (always).
500  *
501  * Environment:
502  *      Nothing interesting.
503  *
504  * Side Effects:
505  *      As advertised.
506  *------------------------------------------------------------------------*/
507 int
508 SRXAFSCB_Probe(struct rx_call *callp)
509 {
510     struct rx_connection *connp;
511     struct rx_peer *peerp;
512     unsigned long host = 0;
513     unsigned short port = 0;
514
515     MUTEX_ENTER(&callp->lock);
516
517     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
518         host = rx_HostOf(peerp);
519         port = rx_PortOf(peerp);
520     }
521
522     osi_Log2(afsd_logp, "SRXAFSCB_Probe from host 0x%x port %d",
523               ntohl(host),
524               ntohs(port));
525
526     MUTEX_EXIT(&callp->lock);
527     return 0;
528 }
529
530 /*------------------------------------------------------------------------
531  * EXPORTED SRXAFSCB_GetLock
532  *
533  * Description:
534  *      Routine called by the server-side callback RPC interface to
535  *      implement pulling out the contents of a lock in the lock
536  *      table.
537  *
538  * Arguments:
539  *      a_call   : Ptr to Rx call on which this request came in.
540  *      a_index  : Index of desired lock.
541  *      a_result : Ptr to a buffer for the given lock.
542  *
543  * Returns:
544  *      0 if everything went fine,
545  *      1 if we were given a bad index.
546  *
547  * Environment:
548  *      Nothing interesting.
549  *
550  * Side Effects:
551  *      As advertised.
552  *------------------------------------------------------------------------*/
553 /* debug interface */
554
555 extern osi_rwlock_t cm_aclLock;
556 extern osi_rwlock_t buf_globalLock;
557 extern osi_rwlock_t cm_callbackLock;
558 extern osi_rwlock_t cm_cellLock;
559 extern osi_rwlock_t cm_connLock;
560 extern osi_rwlock_t cm_daemonLock;
561 extern osi_rwlock_t cm_dnlcLock;
562 extern osi_rwlock_t cm_scacheLock;
563 extern osi_rwlock_t cm_serverLock;
564 extern osi_rwlock_t cm_userLock;
565 extern osi_rwlock_t cm_utilsLock;
566 extern osi_rwlock_t cm_volumeLock;
567 extern osi_rwlock_t smb_globalLock;
568 extern osi_rwlock_t smb_rctLock;
569
570 extern osi_mutex_t cm_Freelance_Lock;
571 extern osi_mutex_t cm_bufGetMutex;
572 extern osi_mutex_t cm_Afsdsbmt_Lock;
573 extern osi_mutex_t tokenEventLock;
574 extern osi_mutex_t  smb_ListenerLock;
575 extern osi_mutex_t smb_RawBufLock;
576 extern osi_mutex_t smb_Dir_Watch_Lock;
577
578 #define LOCKTYPE_RW     1
579 #define LOCKTYPE_MUTEX  2
580 static struct _ltable {
581     char *name;
582     char *addr;
583     int  type;
584 } ltable[] = {
585     {"cm_scacheLock",    (char*)&cm_scacheLock,         LOCKTYPE_RW},
586     {"buf_globalLock",   (char*)&buf_globalLock,        LOCKTYPE_RW},
587     {"cm_serverLock",    (char*)&cm_serverLock,         LOCKTYPE_RW},
588     {"cm_callbackLock",  (char*)&cm_callbackLock,       LOCKTYPE_RW},
589     {"cm_aclLock",       (char*)&cm_aclLock,            LOCKTYPE_RW},
590     {"cm_cellLock",      (char*)&cm_cellLock,           LOCKTYPE_RW},
591     {"cm_connLock",      (char*)&cm_connLock,           LOCKTYPE_RW},
592     {"cm_userLock",      (char*)&cm_userLock,           LOCKTYPE_RW},
593     {"cm_volumeLock",    (char*)&cm_volumeLock,         LOCKTYPE_RW},
594     {"cm_daemonLock",    (char*)&cm_daemonLock,         LOCKTYPE_RW},
595     {"cm_dnlcLock",      (char*)&cm_dnlcLock,           LOCKTYPE_RW},
596     {"cm_utilsLock",     (char*)&cm_utilsLock,          LOCKTYPE_RW},
597     {"smb_globalLock",   (char*)&smb_globalLock,        LOCKTYPE_RW},
598     {"smb_rctLock",      (char*)&smb_rctLock,           LOCKTYPE_RW},
599     {"cm_Freelance_Lock",(char*)&cm_Freelance_Lock,     LOCKTYPE_MUTEX},
600     {"cm_bufGetMutex",   (char*)&cm_bufGetMutex,        LOCKTYPE_MUTEX},
601     {"cm_Afsdsbmt_Lock", (char*)&cm_Afsdsbmt_Lock,      LOCKTYPE_MUTEX},
602     {"tokenEventLock",   (char*)&tokenEventLock,        LOCKTYPE_MUTEX},
603     {"smb_ListenerLock", (char*)&smb_ListenerLock,      LOCKTYPE_MUTEX},
604     {"smb_RawBufLock",   (char*)&smb_RawBufLock,        LOCKTYPE_MUTEX},
605     {"smb_Dir_Watch_Lock",(char*)&smb_Dir_Watch_Lock,   LOCKTYPE_MUTEX}
606 };
607
608 int
609 SRXAFSCB_GetLock(struct rx_call *callp, long index, AFSDBLock *lockp)
610 {
611     struct _ltable *tl;          /*Ptr to lock table entry */
612     osi_rwlock_t  *rwp;
613     osi_mutex_t   *mtxp;
614     int nentries;               /*Num entries in table */
615     int code;                   /*Return code */
616     struct rx_connection *connp;
617     struct rx_peer *peerp;
618     unsigned long host = 0;
619     unsigned short port = 0;
620
621     MUTEX_ENTER(&callp->lock);
622
623     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
624         host = rx_HostOf(peerp);
625         port = rx_PortOf(peerp);
626     }
627
628     osi_Log3(afsd_logp, "SRXAFSCB_GetLock(%d) from host 0x%x port %d", 
629              index, ntohl(host), ntohs(port));
630
631     nentries = sizeof(ltable) / sizeof(struct _ltable);
632     if (index < 0 || index >= nentries) {
633         /*
634          * Past EOF
635          */
636         code = 1;
637     } else {
638         /*
639          * Found it - copy out its contents.
640          */
641         tl = &ltable[index];
642         strncpy(lockp->name, tl->name, sizeof(lockp->name));
643         lockp->name[sizeof(lockp->name)-1] = '\0';
644         lockp->lock.waitStates = 0;
645         switch ( tl->type ) {
646         case LOCKTYPE_RW:
647             rwp = (osi_rwlock_t *)tl->addr;
648             lockp->lock.exclLocked = rwp->flags;
649             lockp->lock.readersReading = rwp->readers;
650             lockp->lock.numWaiting = rwp->waiters;
651             break;
652         case LOCKTYPE_MUTEX:
653             mtxp = (osi_mutex_t *)tl->addr;
654             lockp->lock.exclLocked = mtxp->flags;
655             lockp->lock.readersReading = 0;
656             lockp->lock.numWaiting = mtxp->waiters;
657             break;
658         }
659         lockp->lock.pid_last_reader = 0;
660         lockp->lock.pid_writer = 0;
661         lockp->lock.src_indicator = 0;
662         code = 0;
663     }
664
665     MUTEX_EXIT(&callp->lock);
666     return code;
667 }
668
669 /* debug interface */
670 int
671 SRXAFSCB_GetCE(struct rx_call *callp, long index, AFSDBCacheEntry *cep)
672 {
673     int i;
674     cm_scache_t * scp;
675     int code;
676     struct rx_connection *connp;
677     struct rx_peer *peerp;
678     unsigned long host = 0;
679     unsigned short port = 0;
680
681     MUTEX_ENTER(&callp->lock);
682
683     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
684         host = rx_HostOf(peerp);
685         port = rx_PortOf(peerp);
686     }
687
688     osi_Log2(afsd_logp, "SRXAFSCB_GetCE from host 0x%x port %d",
689              ntohl(host), ntohs(port));
690
691     lock_ObtainRead(&cm_scacheLock);
692     for (i = 0; i < cm_data.hashTableSize; i++) {
693         for (scp = cm_data.hashTablep[i]; scp; scp = scp->nextp) {
694             if (index == 0)
695                 goto searchDone;
696             index--;
697         }                       /*Zip through current hash chain */
698     }                           /*Zip through hash chains */
699
700   searchDone:
701     if (scp == NULL) {
702         /*Past EOF */
703         code = 1;
704         goto fcnDone;
705     }
706
707     /*
708      * Copy out the located entry.
709      */
710     memset(cep, 0, sizeof(AFSDBCacheEntry));
711     cep->addr = afs_data_pointer_to_int32(scp);
712     cep->cell = scp->fid.cell;
713     cep->netFid.Volume = scp->fid.volume;
714     cep->netFid.Vnode = scp->fid.vnode;
715     cep->netFid.Unique = scp->fid.unique;
716     cep->lock.waitStates = 0;
717     cep->lock.exclLocked = scp->mx.flags;
718     cep->lock.readersReading = 0;
719     cep->lock.numWaiting = scp->mx.waiters;
720     cep->lock.pid_last_reader = 0;
721     cep->lock.pid_writer = 0;
722     cep->lock.src_indicator = 0;
723     cep->Length = scp->length.LowPart;
724     cep->DataVersion = scp->dataVersion;
725     cep->callback = afs_data_pointer_to_int32(scp->cbServerp);
726     cep->cbExpires = scp->cbExpires;
727     cep->refCount = scp->refCount;
728     cep->opens = scp->openReads;
729     cep->writers = scp->openWrites;
730     switch (scp->fileType) {
731     case CM_SCACHETYPE_FILE:
732         cep->mvstat = 0;
733         break;
734     case CM_SCACHETYPE_MOUNTPOINT:
735         cep->mvstat = 1;
736         break;
737     case CM_SCACHETYPE_DIRECTORY:
738         if (scp->fid.vnode == 1 && scp->fid.unique == 1)
739             cep->mvstat = 2;
740         else
741             cep->mvstat = 3;
742         break;
743     case CM_SCACHETYPE_SYMLINK:
744         cep->mvstat = 4;
745         break;
746     case CM_SCACHETYPE_DFSLINK:
747         cep->mvstat = 5;
748         break;
749     case CM_SCACHETYPE_INVALID:
750         cep->mvstat = 6;
751         break;
752     }
753     cep->states = 0;
754     if (scp->flags & CM_SCACHEFLAG_STATD)
755         cep->states |= 1;
756     if (scp->flags & CM_SCACHEFLAG_RO || scp->flags & CM_SCACHEFLAG_PURERO)
757         cep->states |= 4;
758     if (scp->fileType == CM_SCACHETYPE_MOUNTPOINT &&
759         scp->mountPointStringp[0])
760         cep->states |= 8;
761     if (scp->flags & CM_SCACHEFLAG_WAITING)
762         cep->states |= 0x40;
763     code = 0;
764
765     /*
766      * Return our results.
767      */
768   fcnDone:
769     lock_ReleaseRead(&cm_scacheLock);
770
771     MUTEX_EXIT(&callp->lock);
772     return (code);
773 }
774
775 /* debug interface */
776 int
777 SRXAFSCB_GetCE64(struct rx_call *callp, long index, AFSDBCacheEntry64 *cep)
778 {
779     int i;
780     cm_scache_t * scp;
781     int code;
782     struct rx_connection *connp;
783     struct rx_peer *peerp;
784     unsigned long host = 0;
785     unsigned short port = 0;
786
787     MUTEX_ENTER(&callp->lock);
788
789     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
790         host = rx_HostOf(peerp);
791         port = rx_PortOf(peerp);
792     }
793
794     osi_Log2(afsd_logp, "SRXAFSCB_GetCE64 from host 0x%x port %d",
795              ntohl(host), ntohs(port));
796
797     lock_ObtainRead(&cm_scacheLock);
798     for (i = 0; i < cm_data.hashTableSize; i++) {
799         for (scp = cm_data.hashTablep[i]; scp; scp = scp->nextp) {
800             if (index == 0)
801                 goto searchDone;
802             index--;
803         }                       /*Zip through current hash chain */
804     }                           /*Zip through hash chains */
805
806   searchDone:
807     if (scp == NULL) {
808         /*Past EOF */
809         code = 1;
810         goto fcnDone;
811     }
812
813     /*
814      * Copy out the located entry.
815      */
816     memset(cep, 0, sizeof(AFSDBCacheEntry64));
817     cep->addr = afs_data_pointer_to_int32(scp);
818     cep->cell = scp->fid.cell;
819     cep->netFid.Volume = scp->fid.volume;
820     cep->netFid.Vnode = scp->fid.vnode;
821     cep->netFid.Unique = scp->fid.unique;
822     cep->lock.waitStates = 0;
823     cep->lock.exclLocked = scp->mx.flags;
824     cep->lock.readersReading = 0;
825     cep->lock.numWaiting = scp->mx.waiters;
826     cep->lock.pid_last_reader = 0;
827     cep->lock.pid_writer = 0;
828     cep->lock.src_indicator = 0;
829 #if !defined(AFS_64BIT_ENV)
830     cep->Length.high = scp->length.HighPart;
831     cep->Length.low = scp->length.LowPart;
832 #else
833     cep->Length = (afs_int64) scp->length.QuadPart;
834 #endif
835     cep->DataVersion = scp->dataVersion;
836     cep->callback = afs_data_pointer_to_int32(scp->cbServerp);
837     cep->cbExpires = scp->cbExpires;
838     cep->refCount = scp->refCount;
839     cep->opens = scp->openReads;
840     cep->writers = scp->openWrites;
841     switch (scp->fileType) {
842     case CM_SCACHETYPE_FILE:
843         cep->mvstat = 0;
844         break;
845     case CM_SCACHETYPE_MOUNTPOINT:
846         cep->mvstat = 1;
847         break;
848     case CM_SCACHETYPE_DIRECTORY:
849         if (scp->fid.vnode == 1 && scp->fid.unique == 1)
850             cep->mvstat = 2;
851         else
852             cep->mvstat = 3;
853         break;
854     case CM_SCACHETYPE_SYMLINK:
855         cep->mvstat = 4;
856         break;
857     case CM_SCACHETYPE_DFSLINK:
858         cep->mvstat = 5;
859         break;
860     case CM_SCACHETYPE_INVALID:
861         cep->mvstat = 6;
862         break;
863     }
864     cep->states = 0;
865     if (scp->flags & CM_SCACHEFLAG_STATD)
866         cep->states |= 1;
867     if (scp->flags & CM_SCACHEFLAG_RO || scp->flags & CM_SCACHEFLAG_PURERO)
868         cep->states |= 4;
869     if (scp->fileType == CM_SCACHETYPE_MOUNTPOINT &&
870         scp->mountPointStringp[0])
871         cep->states |= 8;
872     if (scp->flags & CM_SCACHEFLAG_WAITING)
873         cep->states |= 0x40;
874     code = 0;
875
876     /*
877      * Return our results.
878      */
879   fcnDone:
880     lock_ReleaseRead(&cm_scacheLock);
881
882     MUTEX_EXIT(&callp->lock);
883     return (code);
884 }
885
886 /* debug interface: not implemented */
887 int
888 SRXAFSCB_XStatsVersion(struct rx_call *callp, long *vp)
889 {
890     struct rx_connection *connp;
891     struct rx_peer *peerp;
892     unsigned long host = 0;
893     unsigned short port = 0;
894
895     MUTEX_ENTER(&callp->lock);
896
897     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
898         host = rx_HostOf(peerp);
899         port = rx_PortOf(peerp);
900     }
901
902     osi_Log2(afsd_logp, "SRXAFSCB_XStatsVersion from host 0x%x port %d - not implemented",
903              ntohl(host), ntohs(port));
904     *vp = -1;
905
906     MUTEX_EXIT(&callp->lock);
907     return RXGEN_OPCODE;
908 }
909
910 /* debug interface: not implemented */
911 int
912 SRXAFSCB_GetXStats(struct rx_call *callp, long cvn, long coln, long *srvp, long *timep,
913                    AFSCB_CollData *datap)
914 {
915     struct rx_connection *connp;
916     struct rx_peer *peerp;
917     unsigned long host = 0;
918     unsigned short port = 0;
919
920     MUTEX_ENTER(&callp->lock);
921
922     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
923         host = rx_HostOf(peerp);
924         port = rx_PortOf(peerp);
925     }
926
927     osi_Log2(afsd_logp, "SRXAFSCB_GetXStats from host 0x%x port %d - not implemented",
928              ntohl(host), ntohs(port));
929
930     MUTEX_EXIT(&callp->lock);
931     return RXGEN_OPCODE;
932 }
933
934 int
935 SRXAFSCB_InitCallBackState2(struct rx_call *callp, struct interfaceAddr* addr)
936 {
937     osi_Log0(afsd_logp, "SRXAFSCB_InitCallBackState2 ->");
938
939     return SRXAFSCB_InitCallBackState(callp);
940 }
941
942 /* debug interface */
943 int
944 SRXAFSCB_WhoAreYou(struct rx_call *callp, struct interfaceAddr* addr)
945 {
946     int i;
947     int cm_noIPAddr;         /* number of client network interfaces */
948     int cm_IPAddr[CM_MAXINTERFACE_ADDR];    /* client's IP address in host order */
949     int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
950     int cm_NetMtu[CM_MAXINTERFACE_ADDR];    /* client's MTU sizes */
951     int cm_NetFlags[CM_MAXINTERFACE_ADDR];  /* network flags */
952     long code;
953     struct rx_connection *connp;
954     struct rx_peer *peerp;
955     unsigned long host = 0;
956     unsigned short port = 0;
957
958     MUTEX_ENTER(&callp->lock);
959
960     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
961         host = rx_HostOf(peerp);
962         port = rx_PortOf(peerp);
963     }
964
965     /* get network related info */
966     cm_noIPAddr = CM_MAXINTERFACE_ADDR;
967     code = syscfg_GetIFInfo(&cm_noIPAddr,
968                              cm_IPAddr, cm_SubnetMask,
969                              cm_NetMtu, cm_NetFlags);
970
971     /* return all network interface addresses */
972     osi_Log2(afsd_logp, "SRXAFSCB_WhoAreYou from host 0x%x port %d",
973               ntohl(host),
974               ntohs(port));
975
976     addr->numberOfInterfaces = cm_noIPAddr;
977     addr->uuid = cm_data.Uuid;
978     for ( i=0; i < cm_noIPAddr; i++ ) {
979         addr->addr_in[i] = cm_IPAddr[i];
980         addr->subnetmask[i] = cm_SubnetMask[i];
981         addr->mtu[i] = (rx_mtu == -1 || (rx_mtu != -1 && cm_NetMtu[i] < rx_mtu)) ? 
982             cm_NetMtu[i] : rx_mtu;
983     }
984
985     MUTEX_EXIT(&callp->lock);
986     return 0;
987 }
988
989 int
990 SRXAFSCB_InitCallBackState3(struct rx_call *callp, afsUUID* serverUuid)
991 {
992     char *p = NULL;
993
994     if (UuidToString((UUID *)serverUuid, &p) == RPC_S_OK) {
995         osi_Log1(afsd_logp, "SRXAFSCB_InitCallBackState3 %s ->",p);
996         RpcStringFree(&p);
997     } else
998         osi_Log0(afsd_logp, "SRXAFSCB_InitCallBackState3 - no server Uuid ->");
999
1000     return SRXAFSCB_InitCallBackState(callp);
1001 }
1002
1003 /* debug interface */
1004 int
1005 SRXAFSCB_ProbeUuid(struct rx_call *callp, afsUUID* clientUuid)
1006 {
1007     struct rx_connection *connp;
1008     struct rx_peer *peerp;
1009     unsigned long host = 0;
1010     unsigned short port = 0;
1011     char *p,*q;
1012     int code = 0;
1013
1014     MUTEX_ENTER(&callp->lock);
1015
1016     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1017         host = rx_HostOf(peerp);
1018         port = rx_PortOf(peerp);
1019     }
1020
1021     if ( !afs_uuid_equal(&cm_data.Uuid, clientUuid) ) {
1022         UuidToString((UUID *)&cm_data.Uuid, &p);
1023         UuidToString((UUID *)clientUuid, &q);
1024         osi_Log4(afsd_logp, "SRXAFSCB_ProbeUuid %s != %s from host 0x%x port %d", 
1025                   osi_LogSaveString(afsd_logp,p), 
1026                   osi_LogSaveString(afsd_logp,q),
1027                   ntohl(host),
1028                   ntohs(port));
1029         RpcStringFree(&p);
1030         RpcStringFree(&q);
1031
1032         code = 1;       /* failure */
1033     } else
1034         osi_Log2(afsd_logp, "SRXAFSCB_ProbeUuid (success) from host 0x%x port %d",
1035                   ntohl(host),
1036                   ntohs(port));
1037
1038     MUTEX_EXIT(&callp->lock);
1039     return code;
1040 }
1041
1042 /* debug interface */
1043 int 
1044 SRXAFSCB_GetCellByNum(struct rx_call *callp, afs_int32 a_cellnum,
1045                       char **a_name, serverList *a_hosts)
1046 {
1047     afs_int32 sn;
1048     cm_cell_t * cellp;
1049     cm_serverRef_t * serverRefp; 
1050     struct rx_connection *connp;
1051     struct rx_peer *peerp;
1052     unsigned long host = 0;
1053     unsigned short port = 0;
1054
1055     MUTEX_ENTER(&callp->lock);
1056
1057     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1058         host = rx_HostOf(peerp);
1059         port = rx_PortOf(peerp);
1060     }
1061
1062     osi_Log3(afsd_logp, "SRXAFSCB_GetCellByNum(%d) from host 0x%x port %d",
1063              a_cellnum, ntohl(host), ntohs(port));
1064
1065     a_hosts->serverList_val = 0;
1066     a_hosts->serverList_len = 0;
1067
1068     cellp = cm_FindCellByID(a_cellnum);
1069     if (!cellp) {
1070         *a_name = strdup("");
1071         MUTEX_EXIT(&callp->lock);
1072         return 0;
1073     }
1074
1075     lock_ObtainRead(&cm_serverLock);
1076     *a_name = strdup(cellp->name);
1077
1078     for ( sn = 0, serverRefp = cellp->vlServersp; 
1079           sn < AFSMAXCELLHOSTS && serverRefp;
1080           sn++, serverRefp = serverRefp->next);
1081
1082     a_hosts->serverList_len = sn;
1083     a_hosts->serverList_val = (afs_int32 *)osi_Alloc(sn * sizeof(afs_int32));
1084
1085     for ( sn = 0, serverRefp = cellp->vlServersp; 
1086           sn < AFSMAXCELLHOSTS && serverRefp;
1087           sn++, serverRefp = serverRefp->next)
1088     {
1089         a_hosts->serverList_val[sn] = ntohl(serverRefp->server->addr.sin_addr.s_addr);
1090     }
1091
1092     lock_ReleaseRead(&cm_serverLock);
1093     MUTEX_EXIT(&callp->lock);
1094     return 0;
1095 }
1096
1097 /* debug interface */
1098 int 
1099 SRXAFSCB_TellMeAboutYourself( struct rx_call *callp, 
1100                               struct interfaceAddr *addr,
1101                               Capabilities * capabilities)
1102 {
1103     int i;
1104     afs_int32 *dataBuffP;
1105     afs_int32 dataBytes;
1106     int cm_noIPAddr;         /* number of client network interfaces */
1107     int cm_IPAddr[CM_MAXINTERFACE_ADDR];    /* client's IP address in host order */
1108     int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
1109     int cm_NetMtu[CM_MAXINTERFACE_ADDR];    /* client's MTU sizes */
1110     int cm_NetFlags[CM_MAXINTERFACE_ADDR];  /* network flags */
1111     long code;
1112     struct rx_connection *connp;
1113     struct rx_peer *peerp;
1114     unsigned long host = 0;
1115     unsigned short port = 0;
1116
1117     MUTEX_ENTER(&callp->lock);
1118
1119     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1120         host = rx_HostOf(peerp);
1121         port = rx_PortOf(peerp);
1122     }
1123
1124     /* get network related info */
1125     cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1126     code = syscfg_GetIFInfo(&cm_noIPAddr,
1127                              cm_IPAddr, cm_SubnetMask,
1128                              cm_NetMtu, cm_NetFlags);
1129
1130     osi_Log2(afsd_logp, "SRXAFSCB_TellMeAboutYourself from host 0x%x port %d",
1131               ntohl(host),
1132               ntohs(port));
1133
1134     /* return all network interface addresses */
1135     addr->numberOfInterfaces = cm_noIPAddr;
1136     addr->uuid = cm_data.Uuid;
1137     for ( i=0; i < cm_noIPAddr; i++ ) {
1138         addr->addr_in[i] = cm_IPAddr[i];
1139         addr->subnetmask[i] = cm_SubnetMask[i];
1140         addr->mtu[i] = (rx_mtu == -1 || (rx_mtu != -1 && cm_NetMtu[i] < rx_mtu)) ? 
1141             cm_NetMtu[i] : rx_mtu;
1142     }
1143
1144     dataBytes = 1 * sizeof(afs_int32);
1145     dataBuffP = (afs_int32 *) osi_Alloc(dataBytes);
1146     dataBuffP[0] = CLIENT_CAPABILITY_ERRORTRANS;
1147     capabilities->Capabilities_len = dataBytes / sizeof(afs_int32);
1148     capabilities->Capabilities_val = dataBuffP;
1149
1150     MUTEX_EXIT(&callp->lock);
1151     return 0;
1152 }
1153
1154 /*------------------------------------------------------------------------
1155  * EXPORTED SRXAFSCB_GetServerPrefs
1156  *
1157  * Description:
1158  *      Routine to list server preferences used by this client.
1159  *
1160  * Arguments:
1161  *      a_call  : Ptr to Rx call on which this request came in.
1162  *      a_index : Input server index
1163  *      a_srvr_addr  : Output server address (0xffffffff on last server)
1164  *      a_srvr_rank  : Output server rank
1165  *
1166  * Returns:
1167  *      0 on success
1168  *
1169  * Environment:
1170  *      Nothing interesting.
1171  *
1172  * Side Effects:
1173  *      As advertised.
1174  *------------------------------------------------------------------------*/
1175
1176 int SRXAFSCB_GetServerPrefs(
1177     struct rx_call *callp,
1178     afs_int32 a_index,
1179     afs_int32 *a_srvr_addr,
1180     afs_int32 *a_srvr_rank)
1181 {
1182     struct rx_connection *connp;
1183     struct rx_peer *peerp;
1184     unsigned long host = 0;
1185     unsigned short port = 0;
1186
1187     MUTEX_ENTER(&callp->lock);
1188
1189     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1190         host = rx_HostOf(peerp);
1191         port = rx_PortOf(peerp);
1192     }
1193
1194     osi_Log2(afsd_logp, "SRXAFSCB_GetServerPrefs from host 0x%x port %d - not implemented",
1195               ntohl(host),
1196               ntohs(port));
1197
1198     *a_srvr_addr = 0xffffffff;
1199     *a_srvr_rank = 0xffffffff;
1200
1201     MUTEX_EXIT(&callp->lock);
1202     return 0;
1203 }
1204
1205 /*------------------------------------------------------------------------
1206  * EXPORTED SRXAFSCB_GetCellServDB
1207  *
1208  * Description:
1209  *      Routine to list cells configured for this client
1210  *
1211  * Arguments:
1212  *      a_call  : Ptr to Rx call on which this request came in.
1213  *      a_index : Input cell index
1214  *      a_name  : Output cell name ("" on last cell)
1215  *      a_hosts : Output cell database servers
1216  *
1217  * Returns:
1218  *      0 on success
1219  *
1220  * Environment:
1221  *      Nothing interesting.
1222  *
1223  * Side Effects:
1224  *      As advertised.
1225  *------------------------------------------------------------------------*/
1226
1227 int SRXAFSCB_GetCellServDB(struct rx_call *callp, afs_int32 index, char **a_name, 
1228                            serverList *a_hosts)
1229 {
1230     char *t_name;
1231     struct rx_connection *connp;
1232     struct rx_peer *peerp;
1233     unsigned long host = 0;
1234     unsigned short port = 0;
1235
1236     MUTEX_ENTER(&callp->lock);
1237
1238     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1239         host = rx_HostOf(peerp);
1240         port = rx_PortOf(peerp);
1241     }
1242
1243     osi_Log2(afsd_logp, "SRXAFSCB_GetCellServDB from host 0x%x port %d - not implemented",
1244              ntohl(host), ntohs(port));
1245
1246     t_name = (char *)malloc(AFSNAMEMAX);
1247     t_name[0] = '\0';
1248     *a_name = t_name;
1249     a_hosts->serverList_len = 0;
1250
1251     MUTEX_EXIT(&callp->lock);
1252     return 0;
1253 }
1254
1255 /*------------------------------------------------------------------------
1256  * EXPORTED SRXAFSCB_GetLocalCell
1257  *
1258  * Description:
1259  *      Routine to return name of client's local cell
1260  *
1261  * Arguments:
1262  *      a_call  : Ptr to Rx call on which this request came in.
1263  *      a_name  : Output cell name
1264  *
1265  * Returns:
1266  *      0 on success
1267  *
1268  * Environment:
1269  *      Nothing interesting.
1270  *
1271  * Side Effects:
1272  *      As advertised.
1273  *------------------------------------------------------------------------*/
1274
1275 int SRXAFSCB_GetLocalCell(struct rx_call *callp, char **a_name)
1276 {
1277     char *t_name;
1278     struct rx_connection *connp;
1279     struct rx_peer *peerp;
1280     unsigned long host = 0;
1281     unsigned short port = 0;
1282
1283     MUTEX_ENTER(&callp->lock);
1284
1285     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1286         host = rx_HostOf(peerp);
1287         port = rx_PortOf(peerp);
1288     }
1289
1290     osi_Log2(afsd_logp, "SRXAFSCB_GetLocalCell from host 0x%x port %d",
1291              ntohl(host), ntohs(port));
1292
1293     if (cm_data.rootCellp) {
1294         t_name = (char *)malloc(strlen(cm_data.rootCellp->name)+1);
1295         strcpy(t_name, cm_data.rootCellp->name);
1296     } else {
1297         t_name = (char *)malloc(1);
1298         t_name[0] = '\0';
1299     }
1300     *a_name = t_name;
1301
1302     MUTEX_EXIT(&callp->lock);
1303     return 0;
1304 }
1305
1306
1307 /*
1308  * afs_MarshallCacheConfig - marshall client cache configuration
1309  *
1310  * PARAMETERS
1311  *
1312  * IN callerVersion - the rpc stat version of the caller.
1313  *
1314  * IN config - client cache configuration.
1315  *
1316  * OUT ptr - buffer where configuration is marshalled.
1317  *
1318  * RETURN CODES
1319  *
1320  * Returns void.
1321  */
1322 static void afs_MarshallCacheConfig(
1323     afs_uint32 callerVersion,
1324     cm_initparams_v1 *config,
1325     afs_uint32 *ptr)
1326 {
1327     /*
1328      * We currently only support version 1.
1329      */
1330     *(ptr++) = config->nChunkFiles;
1331     *(ptr++) = config->nStatCaches;
1332     *(ptr++) = config->nDataCaches;
1333     *(ptr++) = config->nVolumeCaches;
1334     *(ptr++) = config->firstChunkSize;
1335     *(ptr++) = config->otherChunkSize;
1336     *(ptr++) = config->cacheSize;
1337     *(ptr++) = config->setTime;
1338     *(ptr++) = config->memCache;
1339
1340 }
1341  
1342
1343 /*------------------------------------------------------------------------
1344  * EXPORTED SRXAFSCB_GetCacheConfig
1345  *
1346  * Description:
1347  *      Routine to return parameters used to initialize client cache.
1348  *      Client may request any format version. Server may not return
1349  *      format version greater than version requested by client.
1350  *
1351  * Arguments:
1352  *      a_call:        Ptr to Rx call on which this request came in.
1353  *      callerVersion: Data format version desired by the client.
1354  *      serverVersion: Data format version of output data.
1355  *      configCount:   Number bytes allocated for output data.
1356  *      config:        Client cache configuration.
1357  *
1358  * Returns:
1359  *      0 on success
1360  *
1361  * Environment:
1362  *      Nothing interesting.
1363  *
1364  * Side Effects:
1365  *      As advertised.
1366  *------------------------------------------------------------------------*/
1367
1368 int SRXAFSCB_GetCacheConfig(struct rx_call *callp,
1369                             afs_uint32 callerVersion,
1370                             afs_uint32 *serverVersion,
1371                             afs_uint32 *configCount,
1372                             cacheConfig *config)
1373 {
1374     afs_uint32 *t_config;
1375     size_t allocsize;
1376     extern cm_initparams_v1 cm_initParams;
1377     struct rx_connection *connp;
1378     struct rx_peer *peerp;
1379     unsigned long host = 0;
1380     unsigned short port = 0;
1381
1382     MUTEX_ENTER(&callp->lock);
1383
1384     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1385         host = rx_HostOf(peerp);
1386         port = rx_PortOf(peerp);
1387     }
1388
1389     osi_Log2(afsd_logp, "SRXAFSCB_GetCacheConfig from host 0x%x port %d - version 1 only",
1390              ntohl(host), ntohs(port));
1391
1392     /*
1393      * Currently only support version 1
1394      */
1395     allocsize = sizeof(cm_initparams_v1);
1396     t_config = (afs_uint32 *)malloc(allocsize);
1397
1398     afs_MarshallCacheConfig(callerVersion, &cm_initParams, t_config);
1399
1400     *serverVersion = AFS_CLIENT_RETRIEVAL_FIRST_EDITION;
1401 #ifdef DEBUG
1402 #ifndef SIZE_MAX
1403 #define SIZE_MAX UINT_MAX
1404 #endif
1405     osi_assert(allocsize < SIZE_MAX);
1406 #endif
1407     *configCount = (afs_uint32)allocsize;
1408     config->cacheConfig_val = t_config;
1409     config->cacheConfig_len = (*configCount)/sizeof(afs_uint32);
1410
1411     MUTEX_EXIT(&callp->lock);
1412     return 0;
1413 }
1414
1415 /* called by afsd without any locks to initialize this module */
1416 void cm_InitCallback(void)
1417 {
1418     lock_InitializeRWLock(&cm_callbackLock, "cm_callbackLock");
1419     cm_activeCallbackGrantingCalls = 0;
1420 }
1421
1422 /* called with locked scp; tells us whether we've got a callback.
1423  * Expirations are checked by a background daemon so as to make
1424  * this function as inexpensive as possible
1425  */
1426 int cm_HaveCallback(cm_scache_t *scp)
1427 {
1428 #ifdef AFS_FREELANCE_CLIENT
1429     // yj: we handle callbacks specially for callbacks on the root directory
1430     // Since it's local, we almost always say that we have callback on it
1431     // The only time we send back a 0 is if we're need to initialize or
1432     // reinitialize the fake directory
1433
1434     // There are 2 state variables cm_fakeGettingCallback and cm_fakeDirCallback
1435     // cm_fakeGettingCallback is 1 if we're in the process of initialization and
1436     // hence should return false. it's 0 otherwise
1437     // cm_fakeDirCallback is 0 if we haven't loaded the fake directory, it's 1
1438     // if the fake directory is loaded and this is the first time cm_HaveCallback
1439     // is called since then. We return false in this case to allow cm_GetCallback
1440     // to be called because cm_GetCallback has some initialization work to do.
1441     // If cm_fakeDirCallback is 2, then it means that the fake directory is in
1442     // good shape and we simply return true, provided no change is detected.
1443     int fdc, fgc;
1444
1445     if (cm_freelanceEnabled && 
1446          scp->fid.cell==AFS_FAKE_ROOT_CELL_ID && scp->fid.volume==AFS_FAKE_ROOT_VOL_ID) {
1447         /* if it's something on /afs */
1448         if (!(scp->fid.vnode==0x1 && scp->fid.unique==0x1)) {
1449             /* if it's not root.afs */
1450             return 1;
1451         }
1452
1453         lock_ObtainMutex(&cm_Freelance_Lock);
1454         fdc = cm_fakeDirCallback;
1455         fgc = cm_fakeGettingCallback;
1456         lock_ReleaseMutex(&cm_Freelance_Lock);
1457             
1458         if (fdc==1) {   // first call since init
1459             return 0;
1460         } else if (fdc==2 && !fgc) {    // we're in good shape
1461             if (cm_getLocalMountPointChange()) {        // check for changes
1462                 cm_clearLocalMountPointChange(); // clear the changefile
1463                 lock_ReleaseMutex(&scp->mx);      // this is re-locked in reInitLocalMountPoints
1464                 cm_reInitLocalMountPoints();    // start reinit
1465                 lock_ObtainMutex(&scp->mx);      // now get the lock back 
1466                 return 0;
1467             }
1468             return 1;                   // no change
1469         }
1470         return 0;
1471     }
1472 #endif
1473
1474     if (scp->cbServerp != NULL)
1475         return 1;
1476     else 
1477         return 0;
1478 }
1479
1480 /* need to detect a broken callback that races with our obtaining a callback.
1481  * Need to be able to do this even if we don't know the file ID of the file
1482  * we're breaking the callback on at the time we start the acquisition of the
1483  * callback (as in the case where we are creating a file).
1484  *
1485  * So, we start by writing down the count of the # of callbacks we've received
1486  * so far, and bumping a global counter of the # of callback granting calls
1487  * outstanding (all done under cm_callbackLock).
1488  *
1489  * When we're back from the call, we look at all of the callback revokes with
1490  * counter numbers greater than the one we recorded in our caller's structure,
1491  * and replay those that are higher than when we started the call.
1492  * 
1493  * We free all the structures in the queue when the count of the # of outstanding
1494  * callback-granting calls drops to zero.
1495  *
1496  * We call this function with the scp locked, too, but in its current implementation,
1497  * this knowledge is not used.
1498  */
1499 void cm_StartCallbackGrantingCall(cm_scache_t *scp, cm_callbackRequest_t *cbrp)
1500 {
1501     lock_ObtainWrite(&cm_callbackLock);
1502     cbrp->callbackCount = cm_callbackCount;
1503     cm_activeCallbackGrantingCalls++;
1504     cbrp->startTime = osi_Time();
1505     cbrp->serverp = NULL;
1506     lock_ReleaseWrite(&cm_callbackLock);
1507 }
1508
1509 /* Called at the end of a callback-granting call, to remove the callback
1510  * info from the scache entry, if necessary.
1511  *
1512  * Called with scp locked, so we can discard the callbacks easily with
1513  * this locking hierarchy.
1514  */
1515 void cm_EndCallbackGrantingCall(cm_scache_t *scp, cm_callbackRequest_t *cbrp,
1516                                 AFSCallBack *cbp, long flags)
1517 {
1518     cm_racingRevokes_t *revp;           /* where we are */
1519     cm_racingRevokes_t *nrevp;          /* where we'll be next */
1520     int freeFlag;
1521     cm_server_t * serverp = 0;
1522     int discardScp = 0;
1523
1524     lock_ObtainWrite(&cm_callbackLock);
1525     if (flags & CM_CALLBACK_MAINTAINCOUNT) {
1526         osi_assert(cm_activeCallbackGrantingCalls > 0);
1527     }
1528     else {
1529         osi_assert(cm_activeCallbackGrantingCalls-- > 0);
1530     }
1531     if (cm_activeCallbackGrantingCalls == 0) 
1532         freeFlag = 1;
1533     else 
1534         freeFlag = 0;
1535
1536     /* record the callback; we'll clear it below if we really lose it */
1537     if (cbrp) {
1538         if (scp) {
1539             if (scp->cbServerp != cbrp->serverp) {
1540                 serverp = scp->cbServerp;
1541                 if (!freeFlag)
1542                     cm_GetServer(cbrp->serverp);
1543                 scp->cbServerp = cbrp->serverp;
1544             } else {
1545                 if (freeFlag)
1546                     serverp = cbrp->serverp;
1547             }
1548             scp->cbExpires = cbrp->startTime + cbp->ExpirationTime;
1549         } else {
1550             if (freeFlag)
1551                 serverp = cbrp->serverp;
1552         }
1553         if (freeFlag)
1554             cbrp->serverp = NULL;
1555     }
1556
1557     /* a callback was actually revoked during our granting call, so
1558      * run down the list of revoked fids, looking for ours.
1559      * If activeCallbackGrantingCalls is zero, free the elements, too.
1560      *
1561      * May need to go through entire list just to do the freeing.
1562      */
1563     for (revp = cm_racingRevokesp; revp; revp = nrevp) {
1564         nrevp = (cm_racingRevokes_t *) osi_QNext(&revp->q);
1565         /* if this callback came in later than when we started the
1566          * callback-granting call, and if this fid is the right fid,
1567          * then clear the callback.
1568          */
1569         if (scp && cbrp && cbrp->callbackCount != cm_callbackCount
1570              && revp->callbackCount > cbrp->callbackCount
1571              && (( scp->fid.volume == revp->fid.volume &&
1572                    scp->fid.vnode == revp->fid.vnode &&
1573                    scp->fid.unique == revp->fid.unique)
1574                   ||
1575                   ((revp->flags & CM_RACINGFLAG_CANCELVOL) &&
1576                     scp->fid.volume == revp->fid.volume)
1577                   ||
1578                   (revp->flags & CM_RACINGFLAG_CANCELALL))) {
1579             /* this one matches */
1580             osi_Log4(afsd_logp,
1581                       "Racing revoke scp 0x%p old cbc %d rev cbc %d cur cbc %d",
1582                       scp,
1583                       cbrp->callbackCount, revp->callbackCount,
1584                       cm_callbackCount);
1585             discardScp = 1;
1586         }
1587         if (freeFlag) 
1588             free(revp);
1589     }
1590
1591     /* if we freed the list, zap the pointer to it */
1592     if (freeFlag) 
1593         cm_racingRevokesp = NULL;
1594
1595     lock_ReleaseWrite(&cm_callbackLock);
1596
1597     if ( discardScp ) {
1598         cm_DiscardSCache(scp);
1599         lock_ReleaseMutex(&scp->mx);
1600         cm_CallbackNotifyChange(scp);
1601         lock_ObtainMutex(&scp->mx);
1602     }
1603
1604     if ( serverp ) {
1605         lock_ObtainWrite(&cm_serverLock);
1606         cm_FreeServer(serverp);
1607         lock_ReleaseWrite(&cm_serverLock);
1608     }
1609 }
1610
1611 /* if flags is 1, we want to force the code to make one call, anyway.
1612  * called with locked scp; returns with same.
1613  */
1614 long cm_GetCallback(cm_scache_t *scp, struct cm_user *userp,
1615                     struct cm_req *reqp, long flags)
1616 {
1617     long code = 0;
1618     cm_conn_t *connp = NULL;
1619     AFSFetchStatus afsStatus;
1620     AFSVolSync volSync;
1621     AFSCallBack callback;
1622     AFSFid tfid;
1623     cm_callbackRequest_t cbr;
1624     int mustCall;
1625     cm_fid_t sfid;
1626     struct rx_connection * callp = NULL;
1627     int syncop_done = 0;
1628
1629     osi_Log4(afsd_logp, "GetCallback scp 0x%p cell %d vol %d flags %lX", 
1630              scp, scp->fid.cell, scp->fid.volume, flags);
1631
1632 #ifdef AFS_FREELANCE_CLIENT
1633     // The case where a callback is needed on /afs is handled
1634     // specially. We need to fetch the status by calling
1635     // cm_MergeStatus and mark that cm_fakeDirCallback is 2
1636     if (cm_freelanceEnabled) {
1637         if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
1638              scp->fid.volume==AFS_FAKE_ROOT_VOL_ID &&
1639              scp->fid.unique==0x1 &&
1640              scp->fid.vnode==0x1) {
1641             
1642             // Start by indicating that we're in the process
1643             // of fetching the callback
1644             lock_ObtainMutex(&cm_Freelance_Lock);
1645             osi_Log0(afsd_logp,"cm_getGetCallback fakeGettingCallback=1");
1646             cm_fakeGettingCallback = 1;
1647             lock_ReleaseMutex(&cm_Freelance_Lock);
1648
1649             // Fetch the status info 
1650             cm_MergeStatus(scp, &afsStatus, &volSync, userp, 0);
1651
1652             // Indicate that the callback is not done
1653             lock_ObtainMutex(&cm_Freelance_Lock);
1654             osi_Log0(afsd_logp,"cm_getGetCallback fakeDirCallback=2");
1655             cm_fakeDirCallback = 2;
1656
1657             // Indicate that we're no longer fetching the callback
1658             osi_Log0(afsd_logp,"cm_getGetCallback fakeGettingCallback=0");
1659             cm_fakeGettingCallback = 0;
1660             lock_ReleaseMutex(&cm_Freelance_Lock);
1661
1662             return 0;
1663         }
1664
1665         if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID && scp->fid.volume==AFS_FAKE_ROOT_VOL_ID) {
1666             osi_Log0(afsd_logp,"cm_getcallback should NEVER EVER get here... ");
1667         }
1668     }
1669 #endif /* AFS_FREELANCE_CLIENT */
1670         
1671     mustCall = (flags & 1);
1672     cm_AFSFidFromFid(&tfid, &scp->fid);
1673     while (1) {
1674         if (!mustCall && cm_HaveCallback(scp))
1675             break;
1676
1677         /* turn off mustCall, since it has now forced us past the check above */
1678         mustCall = 0;
1679
1680         /* otherwise, we have to make an RPC to get the status */
1681         if (!syncop_done) {
1682             code = cm_SyncOp(scp, NULL, userp, reqp, 0, 
1683                              CM_SCACHESYNC_FETCHSTATUS | CM_SCACHESYNC_GETCALLBACK);
1684             if (code)
1685                 break;
1686             syncop_done = 1;
1687         }
1688         cm_StartCallbackGrantingCall(scp, &cbr);
1689         sfid = scp->fid;
1690         lock_ReleaseMutex(&scp->mx);
1691                 
1692         /* now make the RPC */
1693         osi_Log4(afsd_logp, "CALL FetchStatus scp 0x%p vol %u vn %u uniq %u", 
1694                  scp, sfid.volume, sfid.vnode, sfid.unique);
1695         do {
1696             code = cm_Conn(&sfid, userp, reqp, &connp);
1697             if (code) 
1698                 continue;
1699
1700             callp = cm_GetRxConn(connp);
1701             code = RXAFS_FetchStatus(callp, &tfid,
1702                                      &afsStatus, &callback, &volSync);
1703             rx_PutConnection(callp);
1704
1705         } while (cm_Analyze(connp, userp, reqp, &sfid, &volSync, NULL,
1706                             &cbr, code));
1707         code = cm_MapRPCError(code, reqp);
1708         if (code)
1709             osi_Log4(afsd_logp, "CALL FetchStatus FAILURE code 0x%x scp 0x%p vol %u vn %u", 
1710                      code, scp, scp->fid.volume, scp->fid.vnode);
1711         else
1712             osi_Log4(afsd_logp, "CALL FetchStatus SUCCESS scp 0x%p vol %u vn %u uniq %u", 
1713                      scp, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
1714
1715         lock_ObtainMutex(&scp->mx);
1716         if (code == 0) {
1717             cm_EndCallbackGrantingCall(scp, &cbr, &callback, 0);
1718             cm_MergeStatus(scp, &afsStatus, &volSync, userp, 0);
1719         } else {
1720             cm_EndCallbackGrantingCall(NULL, &cbr, NULL, 0);
1721         }
1722
1723         /* if we got an error, return to caller */
1724         if (code)
1725             break;
1726     }
1727
1728     if (syncop_done)
1729         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_FETCHSTATUS | CM_SCACHESYNC_GETCALLBACK);
1730     
1731     if (code) {
1732         osi_Log2(afsd_logp, "GetCallback Failed code 0x%x scp 0x%p -->",code, scp);
1733         osi_Log4(afsd_logp, "            cell %u vol %u vn %u uniq %u",
1734                  scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
1735     } else {
1736         osi_Log3(afsd_logp, "GetCallback Complete scp 0x%p cell %d vol %d", 
1737                   scp, scp->fid.cell, scp->fid.volume);
1738     }
1739
1740     return code;
1741 }
1742
1743 /* called periodically by cm_daemon to shut down use of expired callbacks */
1744 void cm_CheckCBExpiration(void)
1745 {
1746     int i;
1747     cm_scache_t *scp;
1748     time_t now;
1749         
1750     osi_Log0(afsd_logp, "CheckCBExpiration");
1751
1752     now = osi_Time();
1753     lock_ObtainWrite(&cm_scacheLock);
1754     for (i=0; i<cm_data.hashTableSize; i++) {
1755         for (scp = cm_data.hashTablep[i]; scp; scp=scp->nextp) {
1756             cm_HoldSCacheNoLock(scp);
1757             if (scp->cbExpires > 0 && (scp->cbServerp == NULL || now > scp->cbExpires)) {
1758                 lock_ReleaseWrite(&cm_scacheLock);
1759                 osi_Log4(afsd_logp, "Callback Expiration Discarding SCache scp 0x%p vol %u vn %u uniq %u", 
1760                           scp, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
1761                 lock_ObtainMutex(&scp->mx);
1762                 cm_DiscardSCache(scp);
1763                 lock_ReleaseMutex(&scp->mx);
1764                 cm_CallbackNotifyChange(scp);
1765                 lock_ObtainWrite(&cm_scacheLock);
1766             }
1767             cm_ReleaseSCacheNoLock(scp);
1768         }
1769     }
1770     lock_ReleaseWrite(&cm_scacheLock);
1771
1772     osi_Log0(afsd_logp, "CheckCBExpiration Complete");
1773 }
1774