Windows: Make idle dead timeout very long
[openafs.git] / src / WINNT / afsd / cm_conn.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 <string.h>
18 #include <malloc.h>
19 #include <osi.h>
20 #include "afsd.h"
21 #include <rx/rx.h>
22 #include <rx/rxkad.h>
23 #include <afs/unified_afs.h>
24 #include <afs/vlserver.h>
25 #include <WINNT/afsreg.h>
26
27 osi_rwlock_t cm_connLock;
28
29 DWORD RDRtimeout = CM_CONN_DEFAULTRDRTIMEOUT;
30 unsigned short ConnDeadtimeout = CM_CONN_CONNDEADTIME;
31 unsigned short HardDeadtimeout = CM_CONN_HARDDEADTIME;
32 unsigned short IdleDeadtimeout = CM_CONN_IDLEDEADTIME;
33 unsigned short NatPingInterval = CM_CONN_NATPINGINTERVAL;
34
35 #define LANMAN_WKS_PARAM_KEY "SYSTEM\\CurrentControlSet\\Services\\lanmanworkstation\\parameters"
36 #define LANMAN_WKS_SESSION_TIMEOUT "SessTimeout"
37 #define LANMAN_WKS_EXT_SESSION_TIMEOUT "ExtendedSessTimeout"
38
39 afs_uint32 cryptall = 0;
40 afs_uint32 cm_anonvldb = 0;
41 afs_uint32 rx_pmtu_discovery = 0;
42
43 void cm_PutConn(cm_conn_t *connp)
44 {
45     afs_int32 refCount = InterlockedDecrement(&connp->refCount);
46     osi_assertx(refCount >= 0, "cm_conn_t refcount underflow");
47 }
48
49 void cm_InitConn(void)
50 {
51     static osi_once_t once;
52     long code;
53     DWORD dwValue;
54     DWORD dummyLen;
55     HKEY parmKey;
56
57     if (osi_Once(&once)) {
58         lock_InitializeRWLock(&cm_connLock, "connection global lock",
59                                LOCK_HIERARCHY_CONN_GLOBAL);
60
61         /* keisa - read timeout value for lanmanworkstation  service.
62          * jaltman - as per
63          *   http://support.microsoft.com:80/support/kb/articles/Q102/0/67.asp&NoWebContent=1
64          * the SessTimeout is a minimum timeout not a maximum timeout.  Therefore,
65          * I believe that the default should not be short.  Instead, we should wait until
66          * RX times out before reporting a timeout to the SMB client.
67          */
68         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, LANMAN_WKS_PARAM_KEY,
69                             0, KEY_QUERY_VALUE, &parmKey);
70         if (code == ERROR_SUCCESS)
71         {
72             BOOL extTimeouts = msftSMBRedirectorSupportsExtendedTimeouts();
73
74             if (extTimeouts) {
75                 /*
76                  * The default value is 1000 seconds.  However, this default
77                  * will not apply to "\\AFS" unless "AFS" is listed in
78                  * ServersWithExtendedSessTimeout which we will add when we
79                  * create the ExtendedSessTimeout value in smb_Init()
80                  */
81                 dummyLen = sizeof(DWORD);
82                 code = RegQueryValueEx(parmKey,
83                                        LANMAN_WKS_EXT_SESSION_TIMEOUT,
84                                         NULL, NULL,
85                                         (BYTE *) &dwValue, &dummyLen);
86                 if (code == ERROR_SUCCESS) {
87                     RDRtimeout = dwValue;
88                     afsi_log("lanmanworkstation : ExtSessTimeout %u", RDRtimeout);
89                 }
90             }
91             if (!extTimeouts || code != ERROR_SUCCESS) {
92                 dummyLen = sizeof(DWORD);
93                 code = RegQueryValueEx(parmKey,
94                                        LANMAN_WKS_SESSION_TIMEOUT,
95                                        NULL, NULL,
96                                        (BYTE *) &dwValue, &dummyLen);
97                 if (code == ERROR_SUCCESS) {
98                     RDRtimeout = dwValue;
99                     afsi_log("lanmanworkstation : SessTimeout %u", RDRtimeout);
100                 }
101             }
102             RegCloseKey(parmKey);
103         }
104
105         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
106                              0, KEY_QUERY_VALUE, &parmKey);
107         if (code == ERROR_SUCCESS) {
108             dummyLen = sizeof(DWORD);
109             code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
110                                     (BYTE *) &dwValue, &dummyLen);
111             if (code == ERROR_SUCCESS) {
112                 ConnDeadtimeout = (unsigned short)dwValue;
113                 afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
114             }
115             dummyLen = sizeof(DWORD);
116             code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
117                                     (BYTE *) &dwValue, &dummyLen);
118             if (code == ERROR_SUCCESS) {
119                 HardDeadtimeout = (unsigned short)dwValue;
120                 afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
121             }
122             dummyLen = sizeof(DWORD);
123             code = RegQueryValueEx(parmKey, "IdleDeadTimeout", NULL, NULL,
124                                     (BYTE *) &dwValue, &dummyLen);
125             if (code == ERROR_SUCCESS) {
126                 IdleDeadtimeout = (unsigned short)dwValue;
127                 afsi_log("IdleDeadTimeout is %d", IdleDeadtimeout);
128             }
129             dummyLen = sizeof(DWORD);
130             code = RegQueryValueEx(parmKey, "NatPingInterval", NULL, NULL,
131                                     (BYTE *) &dwValue, &dummyLen);
132             if (code == ERROR_SUCCESS) {
133                 NatPingInterval = (unsigned short)dwValue;
134             }
135             afsi_log("NatPingInterval is %d", NatPingInterval);
136             RegCloseKey(parmKey);
137         }
138
139         /*
140          * If these values were not set via cpp macro or obtained
141          * from the registry, we use a value that is derived from
142          * the smb redirector session timeout (RDRtimeout).
143          *
144          * The UNIX cache manager uses 120 seconds for the hard dead
145          * timeout and 50 seconds for the connection and idle timeouts.
146          *
147          * We base our values on those while making sure we leave
148          * enough time for overhead.
149          */
150         if (smb_Enabled) {
151             afsi_log("lanmanworkstation : SessTimeout %u", RDRtimeout);
152             if (ConnDeadtimeout == 0) {
153                 ConnDeadtimeout = (unsigned short) ((RDRtimeout / 2) < 50 ? (RDRtimeout / 2) : 50);
154                 afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
155             }
156             if (HardDeadtimeout == 0) {
157                 HardDeadtimeout = (unsigned short) (RDRtimeout > 125 ? 120 : (RDRtimeout - 5));
158                 afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
159             }
160             if (IdleDeadtimeout == 0) {
161                 IdleDeadtimeout = 10 * (unsigned short) HardDeadtimeout;
162                 afsi_log("IdleDeadTimeout is %d", IdleDeadtimeout);
163             }
164         } else {
165             if (ConnDeadtimeout == 0) {
166                 ConnDeadtimeout = CM_CONN_IFS_CONNDEADTIME;
167                 afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
168             }
169             if (HardDeadtimeout == 0) {
170                 HardDeadtimeout = CM_CONN_IFS_HARDDEADTIME;
171                 afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
172             }
173             if (IdleDeadtimeout == 0) {
174                 IdleDeadtimeout = CM_CONN_IFS_IDLEDEADTIME;
175                 afsi_log("IdleDeadTimeout is %d", IdleDeadtimeout);
176             }
177         }
178         osi_EndOnce(&once);
179     }
180 }
181
182 void cm_InitReq(cm_req_t *reqp)
183 {
184         memset(reqp, 0, sizeof(cm_req_t));
185         reqp->startTime = GetTickCount();
186 }
187
188 static long cm_GetServerList(struct cm_fid *fidp, struct cm_user *userp,
189         struct cm_req *reqp, cm_serverRef_t ***serversppp)
190 {
191     long code;
192     cm_volume_t *volp = NULL;
193     cm_cell_t *cellp = NULL;
194
195     if (!fidp) {
196         *serversppp = NULL;
197         return CM_ERROR_INVAL;
198     }
199
200     cellp = cm_FindCellByID(fidp->cell, 0);
201     if (!cellp)
202         return CM_ERROR_NOSUCHCELL;
203
204     code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp, CM_GETVOL_FLAG_CREATE, &volp);
205     if (code)
206         return code;
207
208     *serversppp = cm_GetVolServers(volp, fidp->volume, userp, reqp);
209
210     lock_ObtainRead(&cm_volumeLock);
211     cm_PutVolume(volp);
212     lock_ReleaseRead(&cm_volumeLock);
213     return (*serversppp ? 0 : CM_ERROR_NOSUCHVOLUME);
214 }
215
216 /*
217  * Analyze the error return from an RPC.  Determine whether or not to retry,
218  * and if we're going to retry, determine whether failover is appropriate,
219  * and whether timed backoff is appropriate.
220  *
221  * If the error code is from cm_ConnFromFID() or friends, it will be a CM_ERROR code.
222  * Otherwise it will be an RPC code.  This may be a UNIX code (e.g. EDQUOT), or
223  * it may be an RX code, or it may be a special code (e.g. VNOVOL), or it may
224  * be a security code (e.g. RXKADEXPIRED).
225  *
226  * If the error code is from cm_ConnFromFID() or friends, connp will be NULL.
227  *
228  * For VLDB calls, fidp will be NULL.
229  *
230  * volSyncp and/or cbrp may also be NULL.
231  */
232 int
233 cm_Analyze(cm_conn_t *connp, cm_user_t *userp, cm_req_t *reqp,
234            struct cm_fid *fidp,
235            AFSVolSync *volSyncp,
236            cm_serverRef_t * serversp,
237            cm_callbackRequest_t *cbrp, long errorCode)
238 {
239     cm_server_t *serverp = NULL;
240     cm_serverRef_t **serverspp = NULL;
241     cm_serverRef_t *tsrp;
242     cm_cell_t  *cellp = NULL;
243     cm_ucell_t *ucellp;
244     cm_volume_t * volp = NULL;
245     cm_vol_state_t *statep = NULL;
246     int retry = 0;
247     int free_svr_list = 0;
248     int dead_session;
249     long timeUsed, timeLeft;
250     long code;
251     char addr[16]="unknown";
252     int forcing_new = 0;
253     int location_updated = 0;
254     char *format;
255     DWORD msgID;
256
257     osi_Log2(afsd_logp, "cm_Analyze connp 0x%p, code 0x%x",
258              connp, errorCode);
259
260     /* no locking required, since connp->serverp never changes after
261      * creation */
262     dead_session = (userp->cellInfop == NULL);
263     if (connp)
264         serverp = connp->serverp;
265
266     /* Update callback pointer */
267     if (cbrp && serverp && errorCode == 0) {
268         if (cbrp->serverp) {
269             if ( cbrp->serverp != serverp ) {
270                 lock_ObtainWrite(&cm_serverLock);
271                 cm_PutServerNoLock(cbrp->serverp);
272                 cm_GetServerNoLock(serverp);
273                 lock_ReleaseWrite(&cm_serverLock);
274             }
275         } else {
276             cm_GetServer(serverp);
277         }
278         lock_ObtainWrite(&cm_callbackLock);
279         cbrp->serverp = serverp;
280         lock_ReleaseWrite(&cm_callbackLock);
281     }
282
283     /* if timeout - check that it did not exceed the HardDead timeout
284      * and retry */
285
286     /* timeleft - get it from reqp the same way as cm_ConnByMServers does */
287     timeUsed = (GetTickCount() - reqp->startTime) / 1000;
288     if ( reqp->flags & CM_REQ_SOURCE_SMB )
289         timeLeft = HardDeadtimeout - timeUsed;
290     else
291         timeLeft = 0x0FFFFFFF;
292
293     /* get a pointer to the cell */
294     if (errorCode) {
295         if (cellp == NULL && serverp)
296             cellp = serverp->cellp;
297         if (cellp == NULL && serversp) {
298             struct cm_serverRef * refp;
299             for ( refp=serversp ; cellp == NULL && refp != NULL; refp=refp->next) {
300                 if (refp->status == srv_deleted)
301                     continue;
302                 if ( refp->server )
303                     cellp = refp->server->cellp;
304             }
305         }
306         if (cellp == NULL && fidp) {
307             cellp = cm_FindCellByID(fidp->cell, 0);
308         }
309     }
310
311     if (errorCode == CM_ERROR_TIMEDOUT) {
312         if ( timeLeft > 5 ) {
313             thrd_Sleep(3000);
314             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, cellp);
315             retry = 1;
316         }
317     }
318
319     else if (errorCode == UAEWOULDBLOCK || errorCode == EWOULDBLOCK ||
320               errorCode == UAEAGAIN || errorCode == EAGAIN) {
321         osi_Log0(afsd_logp, "cm_Analyze passed EWOULDBLOCK or EAGAIN.");
322         if ( timeLeft > 5 ) {
323             thrd_Sleep(1000);
324             retry = 1;
325         }
326     }
327
328     /* if there is nosuchvolume, then we have a situation in which a
329      * previously known volume no longer has a set of servers
330      * associated with it.  Either the volume has moved or
331      * the volume has been deleted.  Try to find a new server list
332      * until the timeout period expires.
333      */
334     else if (errorCode == CM_ERROR_NOSUCHVOLUME) {
335         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_NOSUCHVOLUME.");
336         /*
337          * The VNOVOL or VL_NOENT error has already been translated
338          * to CM_ERROR_NOSUCHVOLUME.  There is nothing for us to do.
339          */
340     }
341
342     else if (errorCode == CM_ERROR_ALLDOWN) {
343         /* Servers marked DOWN will be restored by the background daemon
344          * thread as they become available.  The volume status is
345          * updated as the server state changes.
346          */
347         if (fidp) {
348             osi_Log2(afsd_logp, "cm_Analyze passed CM_ERROR_DOWN (FS cell %s vol 0x%x)",
349                       cellp->name, fidp->volume);
350             msgID = MSG_ALL_SERVERS_DOWN;
351             format = "All servers are unreachable when accessing cell %s volume %d.";
352             LogEvent(EVENTLOG_WARNING_TYPE, msgID, cellp->name, fidp->volume);
353         } else {
354             osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLDOWN (VL Server)");
355         }
356     }
357
358     else if (errorCode == CM_ERROR_ALLOFFLINE) {
359         /* Volume instances marked offline will be restored by the
360          * background daemon thread as they become available
361          */
362         if (fidp) {
363             osi_Log2(afsd_logp, "cm_Analyze passed CM_ERROR_ALLOFFLINE (FS cell %s vol 0x%x)",
364                       cellp->name, fidp->volume);
365             msgID = MSG_ALL_SERVERS_OFFLINE;
366             format = "All servers are offline when accessing cell %s volume %d.";
367             LogEvent(EVENTLOG_WARNING_TYPE, msgID, cellp->name, fidp->volume);
368
369             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
370                                       CM_GETVOL_FLAG_NO_LRU_UPDATE,
371                                       &volp);
372             if (code == 0) {
373                 /*
374                  * Do not perform a cm_CheckOfflineVolume() if cm_Analyze()
375                  * was called by cm_CheckOfflineVolumeState().
376                  */
377                 if (!(reqp->flags & CM_REQ_OFFLINE_VOL_CHK) && timeLeft > 7) {
378                     thrd_Sleep(5000);
379
380                     /* cm_CheckOfflineVolume() resets the serverRef state */
381                     if (cm_CheckOfflineVolume(volp, fidp->volume))
382                         retry = 1;
383                 } else {
384                     cm_UpdateVolumeStatus(volp, fidp->volume);
385                 }
386                 lock_ObtainRead(&cm_volumeLock);
387                 cm_PutVolume(volp);
388                 lock_ReleaseRead(&cm_volumeLock);
389                 volp = NULL;
390             }
391         } else {
392             osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLOFFLINE (VL Server)");
393         }
394     }
395     else if (errorCode == CM_ERROR_ALLBUSY) {
396         /* Volumes that are busy cannot be determined to be non-busy
397          * without actually attempting to access them.
398          */
399         if (fidp) { /* File Server query */
400             osi_Log2(afsd_logp, "cm_Analyze passed CM_ERROR_ALLBUSY (FS cell %s vol 0x%x)",
401                      cellp->name, fidp->volume);
402             msgID = MSG_ALL_SERVERS_BUSY;
403             format = "All servers are busy when accessing cell %s volume %d.";
404             LogEvent(EVENTLOG_WARNING_TYPE, msgID, cellp->name, fidp->volume);
405
406             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
407                                      CM_GETVOL_FLAG_NO_LRU_UPDATE,
408                                      &volp);
409             if (code == 0) {
410                 if (timeLeft > 7) {
411                     thrd_Sleep(5000);
412
413                     statep = cm_VolumeStateByID(volp, fidp->volume);
414                     if (statep->state != vl_offline &&
415                          statep->state != vl_busy &&
416                          statep->state != vl_unknown) {
417                         retry = 1;
418                     } else {
419                         if (!serversp) {
420                             code = cm_GetServerList(fidp, userp, reqp, &serverspp);
421                             if (code == 0) {
422                                 serversp = *serverspp;
423                                 free_svr_list = 1;
424                             }
425                         }
426                         lock_ObtainWrite(&cm_serverLock);
427                         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
428                             if (tsrp->status == srv_deleted)
429                                 continue;
430                             if (tsrp->status == srv_busy) {
431                                 tsrp->status = srv_not_busy;
432                             }
433                         }
434                         lock_ReleaseWrite(&cm_serverLock);
435                         if (free_svr_list) {
436                             cm_FreeServerList(serverspp, 0);
437                             serversp = NULL;
438                             free_svr_list = 0;
439                         }
440
441                         cm_UpdateVolumeStatus(volp, fidp->volume);
442                         retry = 1;
443                     }
444                 } else {
445                     cm_UpdateVolumeStatus(volp, fidp->volume);
446                 }
447
448                 lock_ObtainRead(&cm_volumeLock);
449                 cm_PutVolume(volp);
450                 lock_ReleaseRead(&cm_volumeLock);
451                 volp = NULL;
452             }
453         } else {    /* VL Server query */
454             osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLBUSY (VL Server).");
455
456             if (timeLeft > 7) {
457                 thrd_Sleep(5000);
458
459                 if (serversp) {
460                     lock_ObtainWrite(&cm_serverLock);
461                     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
462                         if (tsrp->status == srv_deleted)
463                             continue;
464                         if (tsrp->status == srv_busy) {
465                             tsrp->status = srv_not_busy;
466                         }
467                     }
468                     lock_ReleaseWrite(&cm_serverLock);
469                     retry = 1;
470                 }
471             }
472         }
473     }
474
475     /* special codes:  VBUSY and VRESTARTING */
476     else if (errorCode == VBUSY || errorCode == VRESTARTING) {
477         if (!serversp && fidp) {
478             code = cm_GetServerList(fidp, userp, reqp, &serverspp);
479             if (code == 0) {
480                 serversp = *serverspp;
481                 free_svr_list = 1;
482             }
483         }
484
485         switch ( errorCode ) {
486         case VBUSY:
487             msgID = MSG_SERVER_REPORTS_VBUSY;
488             format = "Server %s reported busy when accessing volume %d in cell %s.";
489             break;
490         case VRESTARTING:
491             msgID = MSG_SERVER_REPORTS_VRESTARTING;
492             format = "Server %s reported restarting when accessing volume %d in cell %s.";
493             break;
494         }
495
496         if (serverp && fidp) {
497             /* Log server being offline for this volume */
498             sprintf(addr, "%d.%d.%d.%d",
499                    ((serverp->addr.sin_addr.s_addr & 0xff)),
500                    ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
501                    ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
502                    ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
503
504             osi_Log3(afsd_logp, format, osi_LogSaveString(afsd_logp,addr), fidp->volume, cellp->name);
505             LogEvent(EVENTLOG_WARNING_TYPE, msgID, addr, fidp->volume, cellp->name);
506         }
507
508         lock_ObtainWrite(&cm_serverLock);
509         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
510             if (tsrp->status == srv_deleted)
511                 continue;
512             if (tsrp->server == serverp && tsrp->status == srv_not_busy) {
513                 tsrp->status = srv_busy;
514                 if (fidp) { /* File Server query */
515                     lock_ReleaseWrite(&cm_serverLock);
516                     code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
517                                              CM_GETVOL_FLAG_NO_LRU_UPDATE,
518                                              &volp);
519                     if (code == 0)
520                         statep = cm_VolumeStateByID(volp, fidp->volume);
521                     lock_ObtainWrite(&cm_serverLock);
522                 }
523                 break;
524             }
525         }
526         lock_ReleaseWrite(&cm_serverLock);
527
528         if (statep) {
529             cm_UpdateVolumeStatus(volp, statep->ID);
530             lock_ObtainRead(&cm_volumeLock);
531             cm_PutVolume(volp);
532             lock_ReleaseRead(&cm_volumeLock);
533             volp = NULL;
534         }
535
536         if (free_svr_list) {
537             cm_FreeServerList(serverspp, 0);
538             serversp = NULL;
539             free_svr_list = 0;
540         }
541         retry = 1;
542     }
543
544     /* special codes:  missing volumes */
545     else if (errorCode == VNOVOL || errorCode == VMOVED || errorCode == VOFFLINE ||
546              errorCode == VSALVAGE || errorCode == VNOSERVICE || errorCode == VIO)
547     {
548         /* In case of timeout */
549         reqp->volumeError = errorCode;
550
551         switch ( errorCode ) {
552         case VNOVOL:
553             msgID = MSG_SERVER_REPORTS_VNOVOL;
554             format = "Server %s reported volume %d in cell %s as not attached (may have been moved or deleted).";
555             break;
556         case VMOVED:
557             msgID = MSG_SERVER_REPORTS_VMOVED;
558             format = "Server %s reported volume %d in cell %s as moved.";
559             break;
560         case VOFFLINE:
561             msgID = MSG_SERVER_REPORTS_VOFFLINE;
562             format = "Server %s reported volume %d in cell %s as offline.";
563             break;
564         case VSALVAGE:
565             msgID = MSG_SERVER_REPORTS_VSALVAGE;
566             format = "Server %s reported volume %d in cell %s as needs salvage.";
567             break;
568         case VNOSERVICE:
569             msgID = MSG_SERVER_REPORTS_VNOSERVICE;
570             format = "Server %s reported volume %d in cell %s as not in service.";
571             break;
572         case VIO:
573             msgID = MSG_SERVER_REPORTS_VIO;
574             format = "Server %s reported volume %d in cell %s as temporarily unaccessible.";
575             break;
576         }
577
578         if (fidp) { /* File Server query */
579             if (serverp) {
580                 /* Log server being unavailable for this volume */
581                 sprintf(addr, "%d.%d.%d.%d",
582                          ((serverp->addr.sin_addr.s_addr & 0xff)),
583                          ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
584                          ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
585                          ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
586
587                 osi_Log3(afsd_logp, format, osi_LogSaveString(afsd_logp,addr), fidp->volume, cellp->name);
588                 LogEvent(EVENTLOG_WARNING_TYPE, msgID, addr, fidp->volume, cellp->name);
589             }
590
591             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
592                                       CM_GETVOL_FLAG_NO_LRU_UPDATE,
593                                       &volp);
594             if (code == 0)
595                 statep = cm_VolumeStateByID(volp, fidp->volume);
596
597             if ((errorCode == VMOVED || errorCode == VNOVOL || errorCode == VOFFLINE) &&
598                 !(reqp->flags & CM_REQ_VOLUME_UPDATED))
599             {
600                 code = cm_ForceUpdateVolume(fidp, userp, reqp);
601                 if (code == 0)
602                     location_updated = 1;
603
604                 /* Even if the update fails, there might still be another replica */
605
606                 reqp->flags |= CM_REQ_VOLUME_UPDATED;
607                 osi_Log3(afsd_logp, "cm_Analyze called cm_ForceUpdateVolume cell %u vol %u code 0x%x",
608                         fidp->cell, fidp->volume, code);
609             }
610
611             if (statep) {
612                 cm_UpdateVolumeStatus(volp, statep->ID);
613                 osi_Log3(afsd_logp, "cm_Analyze NewVolState cell %u vol %u state %u",
614                          fidp->cell, fidp->volume, statep->state);
615             }
616
617             if (volp) {
618                 lock_ObtainRead(&cm_volumeLock);
619                 cm_PutVolume(volp);
620                 lock_ReleaseRead(&cm_volumeLock);
621                 volp = NULL;
622             }
623
624             /*
625              * Mark server offline for this volume or delete the volume
626              * from the server list if it was moved or is not present.
627              */
628             if (!serversp || location_updated) {
629                 code = cm_GetServerList(fidp, userp, reqp, &serverspp);
630                 if (code == 0) {
631                     serversp = *serverspp;
632                     free_svr_list = 1;
633                 }
634             }
635         }
636
637         lock_ObtainWrite(&cm_serverLock);
638         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
639             if (tsrp->status == srv_deleted)
640                 continue;
641
642             sprintf(addr, "%d.%d.%d.%d",
643                      ((tsrp->server->addr.sin_addr.s_addr & 0xff)),
644                      ((tsrp->server->addr.sin_addr.s_addr & 0xff00)>> 8),
645                      ((tsrp->server->addr.sin_addr.s_addr & 0xff0000)>> 16),
646                      ((tsrp->server->addr.sin_addr.s_addr & 0xff000000)>> 24));
647
648             if (cm_ServerEqual(tsrp->server, serverp)) {
649                 /* REDIRECT */
650                 if (errorCode == VMOVED || errorCode == VNOVOL) {
651                     osi_Log2(afsd_logp, "volume %d not present on server %s",
652                              fidp->volume, osi_LogSaveString(afsd_logp,addr));
653                     tsrp->status = srv_deleted;
654                     if (fidp)
655                         cm_RemoveVolumeFromServer(serverp, fidp->volume);
656                 } else {
657                     osi_Log2(afsd_logp, "volume %d instance on server %s marked offline",
658                              fidp->volume, osi_LogSaveString(afsd_logp,addr));
659                     tsrp->status = srv_offline;
660                 }
661                 /* break; */
662             } else {
663                 osi_Log3(afsd_logp, "volume %d exists on server %s with status %u",
664                          fidp->volume, osi_LogSaveString(afsd_logp,addr), tsrp->status);
665             }
666         }
667         lock_ReleaseWrite(&cm_serverLock);
668
669         /* Free the server list before cm_ForceUpdateVolume is called */
670         if (free_svr_list) {
671             cm_FreeServerList(serverspp, 0);
672             serversp = NULL;
673             free_svr_list = 0;
674         }
675
676         if ( timeLeft > 2 )
677             retry = 1;
678     } else if ( errorCode == VNOVNODE ) {
679         if ( fidp ) {
680             cm_scache_t * scp;
681
682             osi_Log4(afsd_logp, "cm_Analyze passed VNOVNODE cell %u vol %u vn %u uniq %u.",
683                       fidp->cell, fidp->volume, fidp->vnode, fidp->unique);
684
685             scp = cm_FindSCache(fidp);
686             if (scp) {
687                 cm_scache_t *pscp = NULL;
688
689                 if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
690                     pscp = cm_FindSCacheParent(scp);
691
692                 lock_ObtainWrite(&scp->rw);
693                 scp->flags |= CM_SCACHEFLAG_DELETED;
694                 lock_ObtainWrite(&cm_scacheLock);
695                 cm_AdjustScacheLRU(scp);
696                 cm_RemoveSCacheFromHashTable(scp);
697                 lock_ReleaseWrite(&cm_scacheLock);
698                 cm_LockMarkSCacheLost(scp);
699                 lock_ReleaseWrite(&scp->rw);
700                 if (RDR_Initialized)
701                     RDR_InvalidateObject(scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique,
702                                           scp->fid.hash, scp->fileType, AFS_INVALIDATE_DELETED);
703                 cm_ReleaseSCache(scp);
704
705                 if (pscp) {
706                     if (cm_HaveCallback(pscp)) {
707                         lock_ObtainWrite(&pscp->rw);
708                         cm_DiscardSCache(pscp);
709                         lock_ReleaseWrite(&pscp->rw);
710
711                         if (RDR_Initialized)
712                             RDR_InvalidateObject(pscp->fid.cell, pscp->fid.volume, pscp->fid.vnode, pscp->fid.unique,
713                                                  pscp->fid.hash, pscp->fileType, AFS_INVALIDATE_EXPIRED);
714
715                     }
716                     cm_ReleaseSCache(pscp);
717                 }
718             }
719         } else {
720             osi_Log0(afsd_logp, "cm_Analyze passed VNOVNODE unknown fid.");
721         }
722     }
723
724     /* RX codes */
725     else if (errorCode == RX_CALL_TIMEOUT) {
726         /* RPC took longer than hardDeadTime or the server
727          * reported idle for longer than idleDeadTime
728          * don't mark server as down but don't retry
729          * this is to prevent the SMB session from timing out
730          * In addition, we log an event to the event log
731          */
732
733         if (serverp) {
734             sprintf(addr, "%d.%d.%d.%d",
735                     ((serverp->addr.sin_addr.s_addr & 0xff)),
736                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
737                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
738                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
739
740             LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_HARD_DEAD_TIME_EXCEEDED, addr);
741             osi_Log1(afsd_logp, "cm_Analyze: hardDeadTime or idleDeadtime exceeded addr[%s]",
742                      osi_LogSaveString(afsd_logp,addr));
743             reqp->tokenIdleErrorServp = serverp;
744             reqp->idleError++;
745         }
746
747         if (timeLeft > 2) {
748             if (!fidp) { /* vldb */
749                 retry = 1;
750             } else { /* file */
751                 cm_volume_t *volp = cm_GetVolumeByFID(fidp);
752                 if (volp) {
753                     if (fidp->volume == cm_GetROVolumeID(volp))
754                         retry = 1;
755                     cm_PutVolume(volp);
756                 }
757             }
758         }
759     }
760     else if (errorCode == RX_MSGSIZE) {
761         /*
762          * RPC failed because a transmitted rx packet
763          * may have grown larger than the path mtu.
764          * Force a retry and the Rx library will try
765          * with a smaller mtu size.
766          */
767
768         if (serverp)
769             sprintf(addr, "%d.%d.%d.%d",
770                     ((serverp->addr.sin_addr.s_addr & 0xff)),
771                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
772                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
773                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
774
775         LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_MSGSIZE_EXCEEDED, addr);
776         osi_Log1(afsd_logp, "cm_Analyze: Path MTU may have been exceeded addr[%s]",
777                  osi_LogSaveString(afsd_logp,addr));
778
779         retry = 1;
780     }
781     else if (errorCode == CM_RX_RETRY_BUSY_CALL) {
782         /*
783          * RPC failed because the selected call channel
784          * is currently busy on the server.  Unconditionally
785          * retry the request so an alternate call channel can be used.
786          */
787         if (serverp)
788             sprintf(addr, "%d.%d.%d.%d",
789                     ((serverp->addr.sin_addr.s_addr & 0xff)),
790                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
791                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
792                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
793
794         LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_BUSY_CALL_CHANNEL, addr);
795         osi_Log1(afsd_logp, "cm_Analyze: Retry RPC due to busy call channel addr[%s]",
796                  osi_LogSaveString(afsd_logp,addr));
797         retry = 1;
798     }
799     else if (errorCode >= -64 && errorCode < 0) {
800         /* mark server as down */
801         if (serverp)
802             sprintf(addr, "%d.%d.%d.%d",
803                     ((serverp->addr.sin_addr.s_addr & 0xff)),
804                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
805                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
806                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
807
808         if (errorCode == RX_CALL_DEAD)
809             osi_Log2(afsd_logp, "cm_Analyze: Rx Call Dead addr[%s] forcedNew[%s]",
810                      osi_LogSaveString(afsd_logp,addr),
811                      (reqp->flags & CM_REQ_NEW_CONN_FORCED ? "yes" : "no"));
812         else
813             osi_Log3(afsd_logp, "cm_Analyze: Rx Misc Error[%d] addr[%s] forcedNew[%s]",
814                      errorCode,
815                      osi_LogSaveString(afsd_logp,addr),
816                      (reqp->flags & CM_REQ_NEW_CONN_FORCED ? "yes" : "no"));
817
818         if (serverp) {
819             lock_ObtainMutex(&serverp->mx);
820             if (errorCode == RX_CALL_DEAD &&
821                 (reqp->flags & CM_REQ_NEW_CONN_FORCED)) {
822                 if (!(serverp->flags & CM_SERVERFLAG_DOWN)) {
823                     _InterlockedOr(&serverp->flags, CM_SERVERFLAG_DOWN);
824                     serverp->downTime = time(NULL);
825                 }
826             } else {
827                 if (reqp->flags & CM_REQ_NEW_CONN_FORCED) {
828                     reqp->tokenIdleErrorServp = serverp;
829                     reqp->tokenError = errorCode;
830                 } else {
831                     reqp->flags |= CM_REQ_NEW_CONN_FORCED;
832                     forcing_new = 1;
833                 }
834             }
835             lock_ReleaseMutex(&serverp->mx);
836             cm_ForceNewConnections(serverp);
837         }
838         if ( timeLeft > 2 )
839             retry = 1;
840     }
841     else if (errorCode == RXKADEXPIRED) {
842         osi_Log1(afsd_logp, "cm_Analyze: rxkad error code 0x%x (RXKADEXPIRED)",
843                  errorCode);
844         if (!dead_session) {
845             lock_ObtainMutex(&userp->mx);
846             ucellp = cm_GetUCell(userp, serverp->cellp);
847             if (ucellp->ticketp) {
848                 free(ucellp->ticketp);
849                 ucellp->ticketp = NULL;
850             }
851             _InterlockedAnd(&ucellp->flags, ~CM_UCELLFLAG_RXKAD);
852             ucellp->gen++;
853             lock_ReleaseMutex(&userp->mx);
854             if ( timeLeft > 2 )
855                 retry = 1;
856         }
857     } else if (errorCode >= ERROR_TABLE_BASE_RXK && errorCode < ERROR_TABLE_BASE_RXK + 256) {
858         char * s = "unknown error";
859         switch ( errorCode ) {
860         case RXKADINCONSISTENCY: s = "RXKADINCONSISTENCY"; break;
861         case RXKADPACKETSHORT  : s = "RXKADPACKETSHORT";   break;
862         case RXKADLEVELFAIL    : s = "RXKADLEVELFAIL";     break;
863         case RXKADTICKETLEN    : s = "RXKADTICKETLEN";     break;
864         case RXKADOUTOFSEQUENCE: s = "RXKADOUTOFSEQUENCE"; break;
865         case RXKADNOAUTH       : s = "RXKADNOAUTH";        break;
866         case RXKADBADKEY       : s = "RXKADBADKEY";        break;
867         case RXKADBADTICKET    : s = "RXKADBADTICKET";     break;
868         case RXKADUNKNOWNKEY   : s = "RXKADUNKNOWNKEY";    break;
869         case RXKADEXPIRED      : s = "RXKADEXPIRED";       break;
870         case RXKADSEALEDINCON  : s = "RXKADSEALEDINCON";   break;
871         case RXKADDATALEN      : s = "RXKADDATALEN";       break;
872         case RXKADILLEGALLEVEL : s = "RXKADILLEGALLEVEL";  break;
873         }
874         osi_Log2(afsd_logp, "cm_Analyze: rxkad error code 0x%x (%s)",
875                   errorCode, s);
876
877         if (serverp) {
878             reqp->tokenIdleErrorServp = serverp;
879             reqp->tokenError = errorCode;
880             retry = 1;
881         }
882     } else if (errorCode >= ERROR_TABLE_BASE_U && errorCode < ERROR_TABLE_BASE_U + 256) {
883         /*
884          * We received a ubik error.  its possible that the server we are
885          * communicating with has a corrupted database or is partitioned
886          * from the rest of the servers and another server might be able
887          * to answer our query.  Therefore, we will retry the request
888          * and force the use of another server.
889          */
890         if (serverp) {
891             reqp->tokenIdleErrorServp = serverp;
892             reqp->tokenError = errorCode;
893             retry = 1;
894         }
895     } else if (errorCode == VICECONNBAD || errorCode == VICETOKENDEAD) {
896         cm_ForceNewConnections(serverp);
897         if ( timeLeft > 2 )
898             retry = 1;
899     } else {
900         if (errorCode) {
901             char * s = "unknown error";
902             switch ( errorCode ) {
903             case VSALVAGE          : s = "VSALVAGE";           break;
904             case VNOVNODE          : s = "VNOVNODE";           break;
905             case VNOVOL            : s = "VNOVOL";             break;
906             case VVOLEXISTS        : s = "VVOLEXISTS";         break;
907             case VNOSERVICE        : s = "VNOSERVICE";         break;
908             case VOFFLINE          : s = "VOFFLINE";           break;
909             case VONLINE           : s = "VONLINE";            break;
910             case VDISKFULL         : s = "VDISKFULL";          break;
911             case VOVERQUOTA        : s = "VOVERQUOTA";         break;
912             case VBUSY             : s = "VBUSY";              break;
913             case VMOVED            : s = "VMOVED";             break;
914             case VIO               : s = "VIO";                break;
915             case VRESTRICTED       : s = "VRESTRICTED";        break;
916             case VRESTARTING       : s = "VRESTARTING";        break;
917             case VREADONLY         : s = "VREADONLY";          break;
918             case EAGAIN            : s = "EAGAIN";             break;
919             case UAEAGAIN          : s = "UAEAGAIN";           break;
920             case EINVAL            : s = "EINVAL";             break;
921             case UAEINVAL          : s = "UAEINVAL";           break;
922             case EACCES            : s = "EACCES";             break;
923             case UAEACCES          : s = "UAEACCES";           break;
924             case ENOENT            : s = "ENOENT";             break;
925             case UAENOENT          : s = "UAENOENT";           break;
926             case EEXIST            : s = "EEXIST";             break;
927             case UAEEXIST          : s = "UAEEXIST";           break;
928             case VICECONNBAD       : s = "VICECONNBAD";        break;
929             case VICETOKENDEAD     : s = "VICETOKENDEAD";      break;
930             case WSAEWOULDBLOCK    : s = "WSAEWOULDBLOCK";     break;
931             case UAEWOULDBLOCK     : s = "UAEWOULDBLOCK";      break;
932             case VL_IDEXIST        : s = "VL_IDEXIST";         break;
933             case VL_IO             : s = "VL_IO";              break;
934             case VL_NAMEEXIST      : s = "VL_NAMEEXIST";       break;
935             case VL_CREATEFAIL     : s = "VL_CREATEFAIL";      break;
936             case VL_NOENT          : s = "VL_NOENT";           break;
937             case VL_EMPTY          : s = "VL_EMPTY";           break;
938             case VL_ENTDELETED     : s = "VL_ENTDELETED";      break;
939             case VL_BADNAME        : s = "VL_BADNAME";         break;
940             case VL_BADINDEX       : s = "VL_BADINDEX";        break;
941             case VL_BADVOLTYPE     : s = "VL_BADVOLTYPE";      break;
942             case VL_BADSERVER      : s = "VL_BADSERVER";       break;
943             case VL_BADPARTITION   : s = "VL_BADPARTITION";    break;
944             case VL_REPSFULL       : s = "VL_REPSFULL";        break;
945             case VL_NOREPSERVER    : s = "VL_NOREPSERVER";     break;
946             case VL_DUPREPSERVER   : s = "VL_DUPREPSERVER";    break;
947             case VL_RWNOTFOUND     : s = "VL_RWNOTFOUND";      break;
948             case VL_BADREFCOUNT    : s = "VL_BADREFCOUNT";     break;
949             case VL_SIZEEXCEEDED   : s = "VL_SIZEEXCEEDED";    break;
950             case VL_BADENTRY       : s = "VL_BADENTRY";        break;
951             case VL_BADVOLIDBUMP   : s = "VL_BADVOLIDBUMP";    break;
952             case VL_IDALREADYHASHED: s = "VL_IDALREADYHASHED"; break;
953             case VL_ENTRYLOCKED    : s = "VL_ENTRYLOCKED";     break;
954             case VL_BADVOLOPER     : s = "VL_BADVOLOPER";      break;
955             case VL_BADRELLOCKTYPE : s = "VL_BADRELLOCKTYPE";  break;
956             case VL_RERELEASE      : s = "VL_RERELEASE";       break;
957             case VL_BADSERVERFLAG  : s = "VL_BADSERVERFLAG";   break;
958             case VL_PERM           : s = "VL_PERM";            break;
959             case VL_NOMEM          : s = "VL_NOMEM";           break;
960             case VL_BADVERSION     : s = "VL_BADVERSION";      break;
961             case VL_INDEXERANGE    : s = "VL_INDEXERANGE";     break;
962             case VL_MULTIPADDR     : s = "VL_MULTIPADDR";      break;
963             case VL_BADMASK        : s = "VL_BADMASK";         break;
964             case CM_ERROR_NOSUCHCELL        : s = "CM_ERROR_NOSUCHCELL";         break;
965             case CM_ERROR_NOSUCHVOLUME      : s = "CM_ERROR_NOSUCHVOLUME";       break;
966             case CM_ERROR_TIMEDOUT          : s = "CM_ERROR_TIMEDOUT";           break;
967             case CM_ERROR_RETRY             : s = "CM_ERROR_RETRY";              break;
968             case CM_ERROR_NOACCESS          : s = "CM_ERROR_NOACCESS";           break;
969             case CM_ERROR_NOSUCHFILE        : s = "CM_ERROR_NOSUCHFILE";         break;
970             case CM_ERROR_STOPNOW           : s = "CM_ERROR_STOPNOW";            break;
971             case CM_ERROR_TOOBIG            : s = "CM_ERROR_TOOBIG";             break;
972             case CM_ERROR_INVAL             : s = "CM_ERROR_INVAL";              break;
973             case CM_ERROR_BADFD             : s = "CM_ERROR_BADFD";              break;
974             case CM_ERROR_BADFDOP           : s = "CM_ERROR_BADFDOP";            break;
975             case CM_ERROR_EXISTS            : s = "CM_ERROR_EXISTS";             break;
976             case CM_ERROR_CROSSDEVLINK      : s = "CM_ERROR_CROSSDEVLINK";       break;
977             case CM_ERROR_BADOP             : s = "CM_ERROR_BADOP";              break;
978             case CM_ERROR_BADPASSWORD       : s = "CM_ERROR_BADPASSWORD";        break;
979             case CM_ERROR_NOTDIR            : s = "CM_ERROR_NOTDIR";             break;
980             case CM_ERROR_ISDIR             : s = "CM_ERROR_ISDIR";              break;
981             case CM_ERROR_READONLY          : s = "CM_ERROR_READONLY";           break;
982             case CM_ERROR_WOULDBLOCK        : s = "CM_ERROR_WOULDBLOCK";         break;
983             case CM_ERROR_QUOTA             : s = "CM_ERROR_QUOTA";              break;
984             case CM_ERROR_SPACE             : s = "CM_ERROR_SPACE";              break;
985             case CM_ERROR_BADSHARENAME      : s = "CM_ERROR_BADSHARENAME";       break;
986             case CM_ERROR_BADTID            : s = "CM_ERROR_BADTID";             break;
987             case CM_ERROR_UNKNOWN           : s = "CM_ERROR_UNKNOWN";            break;
988             case CM_ERROR_NOMORETOKENS      : s = "CM_ERROR_NOMORETOKENS";       break;
989             case CM_ERROR_NOTEMPTY          : s = "CM_ERROR_NOTEMPTY";           break;
990             case CM_ERROR_USESTD            : s = "CM_ERROR_USESTD";             break;
991             case CM_ERROR_REMOTECONN        : s = "CM_ERROR_REMOTECONN";         break;
992             case CM_ERROR_ATSYS             : s = "CM_ERROR_ATSYS";              break;
993             case CM_ERROR_NOSUCHPATH        : s = "CM_ERROR_NOSUCHPATH";         break;
994             case CM_ERROR_CLOCKSKEW         : s = "CM_ERROR_CLOCKSKEW";          break;
995             case CM_ERROR_BADSMB            : s = "CM_ERROR_BADSMB";             break;
996             case CM_ERROR_ALLBUSY           : s = "CM_ERROR_ALLBUSY";            break;
997             case CM_ERROR_NOFILES           : s = "CM_ERROR_NOFILES";            break;
998             case CM_ERROR_PARTIALWRITE      : s = "CM_ERROR_PARTIALWRITE";       break;
999             case CM_ERROR_NOIPC             : s = "CM_ERROR_NOIPC";              break;
1000             case CM_ERROR_BADNTFILENAME     : s = "CM_ERROR_BADNTFILENAME";      break;
1001             case CM_ERROR_BUFFERTOOSMALL    : s = "CM_ERROR_BUFFERTOOSMALL";     break;
1002             case CM_ERROR_RENAME_IDENTICAL  : s = "CM_ERROR_RENAME_IDENTICAL";   break;
1003             case CM_ERROR_ALLOFFLINE        : s = "CM_ERROR_ALLOFFLINE";         break;
1004             case CM_ERROR_AMBIGUOUS_FILENAME: s = "CM_ERROR_AMBIGUOUS_FILENAME"; break;
1005             case CM_ERROR_BADLOGONTYPE      : s = "CM_ERROR_BADLOGONTYPE";       break;
1006             case CM_ERROR_GSSCONTINUE       : s = "CM_ERROR_GSSCONTINUE";        break;
1007             case CM_ERROR_TIDIPC            : s = "CM_ERROR_TIDIPC";             break;
1008             case CM_ERROR_TOO_MANY_SYMLINKS : s = "CM_ERROR_TOO_MANY_SYMLINKS";  break;
1009             case CM_ERROR_PATH_NOT_COVERED  : s = "CM_ERROR_PATH_NOT_COVERED";   break;
1010             case CM_ERROR_LOCK_CONFLICT     : s = "CM_ERROR_LOCK_CONFLICT";      break;
1011             case CM_ERROR_SHARING_VIOLATION : s = "CM_ERROR_SHARING_VIOLATION";  break;
1012             case CM_ERROR_ALLDOWN           : s = "CM_ERROR_ALLDOWN";            break;
1013             case CM_ERROR_TOOFEWBUFS        : s = "CM_ERROR_TOOFEWBUFS";         break;
1014             case CM_ERROR_TOOMANYBUFS       : s = "CM_ERROR_TOOMANYBUFS";        break;
1015             }
1016             osi_Log2(afsd_logp, "cm_Analyze: ignoring error code 0x%x (%s)",
1017                      errorCode, s);
1018             retry = 0;
1019         }
1020     }
1021
1022     /* If not allowed to retry, don't */
1023     if (!forcing_new && (reqp->flags & CM_REQ_NORETRY) &&
1024         (errorCode != RX_MSGSIZE && errorCode != CM_RX_RETRY_BUSY_CALL))
1025         retry = 0;
1026     else if (retry && dead_session)
1027         retry = 0;
1028
1029     /* drop this on the way out */
1030     if (connp)
1031         cm_PutConn(connp);
1032
1033     /*
1034      * clear the volume updated flag if we succeed.
1035      * this way the flag will not prevent a subsequent volume
1036      * from being updated if necessary.
1037      */
1038     if (errorCode == 0)
1039     {
1040         reqp->flags &= ~CM_REQ_VOLUME_UPDATED;
1041     }
1042
1043     /* retry until we fail to find a connection */
1044     return retry;
1045 }
1046
1047 long cm_ConnByMServers(cm_serverRef_t *serversp, cm_user_t *usersp,
1048         cm_req_t *reqp, cm_conn_t **connpp)
1049 {
1050     long code;
1051     cm_serverRef_t *tsrp;
1052     cm_server_t *tsp;
1053     long firstError = 0;
1054     int someBusy = 0, someOffline = 0, allOffline = 1, allBusy = 1, allDown = 1;
1055 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
1056     long timeUsed, timeLeft, hardTimeLeft;
1057 #endif
1058     *connpp = NULL;
1059
1060     if (serversp == NULL) {
1061         osi_Log1(afsd_logp, "cm_ConnByMServers returning 0x%x", CM_ERROR_ALLDOWN);
1062         return CM_ERROR_ALLDOWN;
1063     }
1064
1065 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
1066     timeUsed = (GetTickCount() - reqp->startTime) / 1000;
1067
1068     /* leave 5 seconds margin of safety */
1069     timeLeft =  ConnDeadtimeout - timeUsed - 5;
1070     hardTimeLeft = HardDeadtimeout - timeUsed - 5;
1071 #endif
1072
1073     lock_ObtainRead(&cm_serverLock);
1074     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
1075         if (tsrp->status == srv_deleted)
1076             continue;
1077
1078         tsp = tsrp->server;
1079         if (reqp->tokenIdleErrorServp) {
1080             /*
1081              * search the list until we find the server
1082              * that failed last time.  When we find it
1083              * clear the error, skip it and try the next one
1084              * in the list.
1085              */
1086             if (tsp == reqp->tokenIdleErrorServp)
1087                 reqp->tokenIdleErrorServp = NULL;
1088             continue;
1089         }
1090         if (tsp) {
1091             cm_GetServerNoLock(tsp);
1092             lock_ReleaseRead(&cm_serverLock);
1093             if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
1094                 allDown = 0;
1095                 if (tsrp->status == srv_busy) {
1096                     allOffline = 0;
1097                     someBusy = 1;
1098                 } else if (tsrp->status == srv_offline) {
1099                     allBusy = 0;
1100                     someOffline = 1;
1101                 } else {
1102                     allOffline = 0;
1103                     allBusy = 0;
1104                     code = cm_ConnByServer(tsp, usersp, connpp);
1105                     if (code == 0) {        /* cm_CBS only returns 0 */
1106                         cm_PutServer(tsp);
1107 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
1108                         /* Set RPC timeout */
1109                         if (timeLeft > ConnDeadtimeout)
1110                             timeLeft = ConnDeadtimeout;
1111
1112                         if (hardTimeLeft > HardDeadtimeout)
1113                             hardTimeLeft = HardDeadtimeout;
1114
1115                         lock_ObtainMutex(&(*connpp)->mx);
1116                         rx_SetConnDeadTime((*connpp)->rxconnp, timeLeft);
1117                         rx_SetConnHardDeadTime((*connpp)->rxconnp, (u_short) hardTimeLeft);
1118                         lock_ReleaseMutex(&(*connpp)->mx);
1119 #endif
1120                         return 0;
1121                     }
1122
1123                     /* therefore, this code is never executed */
1124                     if (firstError == 0)
1125                         firstError = code;
1126                 }
1127             }
1128             lock_ObtainRead(&cm_serverLock);
1129             cm_PutServerNoLock(tsp);
1130         }
1131     }
1132     lock_ReleaseRead(&cm_serverLock);
1133
1134     if (firstError == 0) {
1135         if (allDown) {
1136             firstError = (reqp->tokenError ? reqp->tokenError :
1137                           (reqp->idleError ? RX_CALL_TIMEOUT : CM_ERROR_ALLDOWN));
1138             /*
1139              * if we experienced either a token error or and idle dead time error
1140              * and now all of the servers are down, we have either tried them
1141              * all or lost connectivity.  Clear the error we are returning so
1142              * we will not return it indefinitely if the request is retried.
1143              */
1144             reqp->idleError = reqp->tokenError = 0;
1145         } else if (allBusy) {
1146             firstError = CM_ERROR_ALLBUSY;
1147         } else if (allOffline || (someBusy && someOffline)) {
1148             firstError = CM_ERROR_ALLOFFLINE;
1149         } else {
1150             osi_Log0(afsd_logp, "cm_ConnByMServers returning impossible error TIMEDOUT");
1151             firstError = CM_ERROR_TIMEDOUT;
1152         }
1153     }
1154
1155     osi_Log1(afsd_logp, "cm_ConnByMServers returning 0x%x", firstError);
1156     return firstError;
1157 }
1158
1159 /* called with a held server to GC all bad connections hanging off of the server */
1160 void cm_GCConnections(cm_server_t *serverp)
1161 {
1162     cm_conn_t *tcp;
1163     cm_conn_t **lcpp;
1164     cm_user_t *userp;
1165
1166     lock_ObtainWrite(&cm_connLock);
1167     lcpp = &serverp->connsp;
1168     for (tcp = *lcpp; tcp; tcp = *lcpp) {
1169         userp = tcp->userp;
1170         if (userp && tcp->refCount == 0 && (userp->vcRefs == 0)) {
1171             /* do the deletion of this guy */
1172             cm_PutServer(tcp->serverp);
1173             cm_ReleaseUser(userp);
1174             *lcpp = tcp->nextp;
1175             rx_SetConnSecondsUntilNatPing(tcp->rxconnp, 0);
1176             rx_DestroyConnection(tcp->rxconnp);
1177             lock_FinalizeMutex(&tcp->mx);
1178             free(tcp);
1179         }
1180         else {
1181             /* just advance to the next */
1182             lcpp = &tcp->nextp;
1183         }
1184     }
1185     lock_ReleaseWrite(&cm_connLock);
1186 }
1187
1188 static void cm_NewRXConnection(cm_conn_t *tcp, cm_ucell_t *ucellp,
1189                                cm_server_t *serverp)
1190 {
1191     unsigned short port;
1192     int serviceID;
1193     int secIndex;
1194     struct rx_securityClass *secObjp;
1195
1196     port = serverp->addr.sin_port;
1197     switch (serverp->type) {
1198     case CM_SERVER_VLDB:
1199         if (port == 0)
1200             port = htons(7003);
1201         serviceID = 52;
1202         break;
1203     case CM_SERVER_FILE:
1204         if (port == 0)
1205             port = htons(7000);
1206         serviceID = 1;
1207         break;
1208     default:
1209         osi_panic("unknown server type", __FILE__, __LINE__);
1210     }
1211
1212     if (ucellp->flags & CM_UCELLFLAG_RXKAD) {
1213         secIndex = 2;
1214         switch (cryptall) {
1215         case 0:
1216             tcp->cryptlevel = rxkad_clear;
1217             break;
1218         case 2:
1219             tcp->cryptlevel = rxkad_auth;
1220             break;
1221         default:
1222             tcp->cryptlevel = rxkad_crypt;
1223         }
1224         secObjp = rxkad_NewClientSecurityObject(tcp->cryptlevel,
1225                                                 &ucellp->sessionKey, ucellp->kvno,
1226                                                 ucellp->ticketLen, ucellp->ticketp);
1227     } else {
1228         /* normal auth */
1229         secIndex = 0;
1230         tcp->cryptlevel = rxkad_clear;
1231         secObjp = rxnull_NewClientSecurityObject();
1232     }
1233     osi_assertx(secObjp != NULL, "null rx_securityClass");
1234     tcp->rxconnp = rx_NewConnection(serverp->addr.sin_addr.s_addr,
1235                                     port,
1236                                     serviceID,
1237                                     secObjp,
1238                                     secIndex);
1239     rx_SetConnDeadTime(tcp->rxconnp, ConnDeadtimeout);
1240     rx_SetConnHardDeadTime(tcp->rxconnp, HardDeadtimeout);
1241
1242     /* Disable Idle Dead Timeout processing as it can lead to data corruption. */
1243     rx_SetConnIdleDeadTime(tcp->rxconnp, IdleDeadtimeout);
1244
1245     /*
1246      * Register the error to be returned on an idle dead timeout
1247      */
1248     rx_SetServerConnIdleDeadErr(tcp->rxconnp, RX_CALL_DEAD);
1249
1250     /*
1251      * Let the Rx library know that we can auto-retry if an
1252      * RX_MSGSIZE error is returned.
1253      */
1254     if (rx_pmtu_discovery)
1255         rx_SetMsgsizeRetryErr(tcp->rxconnp, RX_MSGSIZE);
1256
1257     /*
1258      * Attempt to limit NAT pings to the anonymous file server connections.
1259      * Only file servers implement client callbacks and we only need one ping
1260      * to be sent to each server.
1261      */
1262     if (NatPingInterval && serverp->type == CM_SERVER_FILE &&
1263          (ucellp->flags & CM_UCELLFLAG_ROOTUSER)) {
1264         rx_SetConnSecondsUntilNatPing(tcp->rxconnp, NatPingInterval);
1265     }
1266
1267     tcp->ucgen = ucellp->gen;
1268     if (secObjp)
1269         rxs_Release(secObjp);   /* Decrement the initial refCount */
1270 }
1271
1272 long cm_ConnByServer(cm_server_t *serverp, cm_user_t *userp, cm_conn_t **connpp)
1273 {
1274     cm_conn_t *tcp;
1275     cm_ucell_t *ucellp;
1276
1277     *connpp = NULL;
1278
1279     if (cm_anonvldb && serverp->type == CM_SERVER_VLDB)
1280         userp = cm_rootUserp;
1281
1282     lock_ObtainMutex(&userp->mx);
1283     lock_ObtainRead(&cm_connLock);
1284     for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1285         if (tcp->userp == userp)
1286             break;
1287     }
1288
1289     /* find ucell structure */
1290     ucellp = cm_GetUCell(userp, serverp->cellp);
1291     if (!tcp) {
1292         lock_ConvertRToW(&cm_connLock);
1293         for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1294             if (tcp->userp == userp)
1295                 break;
1296         }
1297         if (tcp) {
1298             lock_ReleaseWrite(&cm_connLock);
1299             goto haveconn;
1300         }
1301         cm_GetServer(serverp);
1302         tcp = malloc(sizeof(*tcp));
1303         memset(tcp, 0, sizeof(*tcp));
1304         tcp->nextp = serverp->connsp;
1305         serverp->connsp = tcp;
1306         cm_HoldUser(userp);
1307         tcp->userp = userp;
1308         lock_InitializeMutex(&tcp->mx, "cm_conn_t mutex", LOCK_HIERARCHY_CONN);
1309         lock_ObtainMutex(&tcp->mx);
1310         tcp->serverp = serverp;
1311         tcp->cryptlevel = rxkad_clear;
1312         cm_NewRXConnection(tcp, ucellp, serverp);
1313         tcp->refCount = 1;
1314         lock_ReleaseMutex(&tcp->mx);
1315         lock_ReleaseWrite(&cm_connLock);
1316     } else {
1317         lock_ReleaseRead(&cm_connLock);
1318       haveconn:
1319         InterlockedIncrement(&tcp->refCount);
1320
1321         lock_ObtainMutex(&tcp->mx);
1322         if ((tcp->flags & CM_CONN_FLAG_FORCE_NEW) ||
1323             (tcp->ucgen < ucellp->gen) ||
1324             (tcp->cryptlevel != (ucellp->flags & CM_UCELLFLAG_RXKAD ? (cryptall == 1 ? rxkad_crypt : (cryptall == 2 ? rxkad_auth : rxkad_clear)) : rxkad_clear)))
1325         {
1326             if (tcp->ucgen < ucellp->gen)
1327                 osi_Log0(afsd_logp, "cm_ConnByServer replace connection due to token update");
1328             else
1329                 osi_Log0(afsd_logp, "cm_ConnByServer replace connection due to crypt change");
1330             tcp->flags &= ~CM_CONN_FLAG_FORCE_NEW;
1331             rx_SetConnSecondsUntilNatPing(tcp->rxconnp, 0);
1332             rx_DestroyConnection(tcp->rxconnp);
1333             cm_NewRXConnection(tcp, ucellp, serverp);
1334         }
1335         lock_ReleaseMutex(&tcp->mx);
1336     }
1337     lock_ReleaseMutex(&userp->mx);
1338
1339     /* return this pointer to our caller */
1340     osi_Log1(afsd_logp, "cm_ConnByServer returning conn 0x%p", tcp);
1341     *connpp = tcp;
1342
1343     return 0;
1344 }
1345
1346 long cm_ServerAvailable(struct cm_fid *fidp, struct cm_user *userp)
1347 {
1348     long code;
1349     cm_req_t req;
1350     cm_serverRef_t **serverspp;
1351     cm_serverRef_t *tsrp;
1352     cm_server_t *tsp;
1353     int someBusy = 0, someOffline = 0, allOffline = 1, allBusy = 1, allDown = 1;
1354
1355     cm_InitReq(&req);
1356
1357     code = cm_GetServerList(fidp, userp, &req, &serverspp);
1358     if (code)
1359         return 0;
1360
1361     lock_ObtainRead(&cm_serverLock);
1362     for (tsrp = *serverspp; tsrp; tsrp=tsrp->next) {
1363         if (tsrp->status == srv_deleted)
1364             continue;
1365         tsp = tsrp->server;
1366         if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
1367             allDown = 0;
1368             if (tsrp->status == srv_busy) {
1369                 allOffline = 0;
1370                 someBusy = 1;
1371             } else if (tsrp->status == srv_offline) {
1372                 allBusy = 0;
1373                 someOffline = 1;
1374             } else {
1375                 allOffline = 0;
1376                 allBusy = 0;
1377             }
1378         }
1379     }
1380     lock_ReleaseRead(&cm_serverLock);
1381     cm_FreeServerList(serverspp, 0);
1382
1383     if (allDown)
1384         return 0;
1385     else if (allBusy)
1386         return 0;
1387     else if (allOffline || (someBusy && someOffline))
1388         return 0;
1389     else
1390         return 1;
1391 }
1392
1393 /*
1394  * The returned cm_conn_t ** object is released in the subsequent call
1395  * to cm_Analyze().
1396  */
1397 long cm_ConnFromFID(struct cm_fid *fidp, struct cm_user *userp, cm_req_t *reqp,
1398                     cm_conn_t **connpp)
1399 {
1400     long code;
1401     cm_serverRef_t **serverspp;
1402
1403     *connpp = NULL;
1404
1405     code = cm_GetServerList(fidp, userp, reqp, &serverspp);
1406     if (code) {
1407         return code;
1408     }
1409
1410     code = cm_ConnByMServers(*serverspp, userp, reqp, connpp);
1411     cm_FreeServerList(serverspp, 0);
1412     return code;
1413 }
1414
1415
1416 long cm_ConnFromVolume(struct cm_volume *volp, unsigned long volid, struct cm_user *userp, cm_req_t *reqp,
1417                        cm_conn_t **connpp)
1418 {
1419     long code;
1420     cm_serverRef_t **serverspp;
1421
1422     *connpp = NULL;
1423
1424     serverspp = cm_GetVolServers(volp, volid, userp, reqp);
1425
1426     code = cm_ConnByMServers(*serverspp, userp, reqp, connpp);
1427     cm_FreeServerList(serverspp, 0);
1428     return code;
1429 }
1430
1431
1432 extern struct rx_connection *
1433 cm_GetRxConn(cm_conn_t *connp)
1434 {
1435     struct rx_connection * rxconnp;
1436     lock_ObtainMutex(&connp->mx);
1437     rxconnp = connp->rxconnp;
1438     rx_GetConnection(rxconnp);
1439     lock_ReleaseMutex(&connp->mx);
1440     return rxconnp;
1441 }
1442
1443 void cm_ForceNewConnections(cm_server_t *serverp)
1444 {
1445     cm_conn_t *tcp;
1446
1447     lock_ObtainWrite(&cm_connLock);
1448     for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1449         lock_ObtainMutex(&tcp->mx);
1450         tcp->flags |= CM_CONN_FLAG_FORCE_NEW;
1451         lock_ReleaseMutex(&tcp->mx);
1452     }
1453     lock_ReleaseWrite(&cm_connLock);
1454 }