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