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