viced avoid global pruclient during acl ops
[openafs.git] / src / viced / afsfileprocs.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 /*  afs_fileprocs.c - Complete File Server request routines              */
11 /*                                                                       */
12 /*  Information Technology Center                                        */
13 /*  Carnegie Mellon University                                           */
14 /*                                                                       */
15 /*  Date: 8/10/88                                                        */
16 /*                                                                       */
17 /*  Function    - A set of routines to handle the various file Server    */
18 /*                  requests; these routines are invoked by rxgen.       */
19 /*                                                                       */
20 /* ********************************************************************** */
21
22 /* 
23  * in Check_PermissionRights, certain privileges are afforded to the owner 
24  * of the volume, or the owner of a file.  Are these considered "use of 
25  * privilege"? 
26  */
27
28 #include <afsconfig.h>
29 #include <afs/param.h>
30
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <errno.h>
35 #ifdef  AFS_SGI_ENV
36 #undef SHARED                   /* XXX */
37 #endif
38 #ifdef AFS_NT40_ENV
39 #include <fcntl.h>
40 #else
41 #include <sys/param.h>
42 #include <sys/file.h>
43 #include <sys/ioctl.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48 #include <string.h>
49
50 #ifndef AFS_LINUX20_ENV
51 #include <net/if.h>
52 #include <netinet/if_ether.h>
53 #endif
54 #endif
55 #ifdef AFS_HPUX_ENV
56 /* included early because of name conflict on IOPEN */
57 #include <sys/inode.h>
58 #ifdef IOPEN
59 #undef IOPEN
60 #endif
61 #endif /* AFS_HPUX_ENV */
62 #include <afs/stds.h>
63 #include <rx/xdr.h>
64 #include <afs/nfs.h>
65 #include <afs/assert.h>
66 #include <lwp.h>
67 #include <lock.h>
68 #include <afs/afsint.h>
69 #include <afs/vldbint.h>
70 #include <afs/errors.h>
71 #include <afs/ihandle.h>
72 #include <afs/vnode.h>
73 #include <afs/volume.h>
74 #include <afs/ptclient.h>
75 #include <afs/ptuser.h>
76 #include <afs/prs_fs.h>
77 #include <afs/acl.h>
78 #include <rx/rx.h>
79 #include <rx/rx_globals.h>
80 #include <sys/stat.h>
81 #if ! defined(AFS_SGI_ENV) && ! defined(AFS_AIX32_ENV) && ! defined(AFS_NT40_ENV) && ! defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
82 #include <sys/map.h>
83 #endif
84 #if !defined(AFS_NT40_ENV)
85 #include <unistd.h>
86 #endif
87 #if !defined(AFS_SGI_ENV) && !defined(AFS_NT40_ENV)
88 #ifdef  AFS_AIX_ENV
89 #include <sys/statfs.h>
90 #include <sys/lockf.h>
91 #else
92 #if !defined(AFS_SUN5_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
93 #include <sys/dk.h>
94 #endif
95 #endif
96 #endif
97 #include <afs/cellconfig.h>
98 #include <afs/keys.h>
99
100 #include <signal.h>
101 #include <afs/partition.h>
102 #include "viced_prototypes.h"
103 #include "viced.h"
104 #include "host.h"
105 #include "callback.h"
106 #include <afs/unified_afs.h>
107 #include <afs/audit.h>
108 #include <afs/afsutil.h>
109 #include <afs/dir.h>
110
111 extern void SetDirHandle(register DirHandle * dir, register Vnode * vnode);
112 extern void FidZap(DirHandle * file);
113 extern void FidZero(DirHandle * file);
114
115 #ifdef AFS_PTHREAD_ENV
116 pthread_mutex_t fileproc_glock_mutex;
117 #endif /* AFS_PTHREAD_ENV */
118
119 #ifdef O_LARGEFILE
120 #define afs_stat        stat64
121 #define afs_fstat       fstat64
122 #define afs_open        open64
123 #else /* !O_LARGEFILE */
124 #define afs_stat        stat
125 #define afs_fstat       fstat
126 #define afs_open        open
127 #endif /* !O_LARGEFILE */
128
129
130 /* Useful local defines used by this module */
131
132 #define DONTCHECK       0
133 #define MustNOTBeDIR    1
134 #define MustBeDIR       2
135
136 #define TVS_SDATA       1
137 #define TVS_SSTATUS     2
138 #define TVS_CFILE       4
139 #define TVS_SLINK       8
140 #define TVS_MKDIR       0x10
141
142 #define CHK_FETCH       0x10
143 #define CHK_FETCHDATA   0x10
144 #define CHK_FETCHACL    0x11
145 #define CHK_FETCHSTATUS 0x12
146 #define CHK_STOREDATA   0x00
147 #define CHK_STOREACL    0x01
148 #define CHK_STORESTATUS 0x02
149
150 #define OWNERREAD       0400
151 #define OWNERWRITE      0200
152 #define OWNEREXEC       0100
153 #ifdef USE_GROUP_PERMS
154 #define GROUPREAD       0040
155 #define GROUPWRITE      0020
156 #define GROUPREXEC      0010
157 #endif
158
159 /* The following errors were not defined in NT. They are given unique
160  * names here to avoid any potential collision.
161  */
162 #define FSERR_ELOOP              90
163 #define FSERR_EOPNOTSUPP        122
164 #define FSERR_ECONNREFUSED      130
165
166 #define NOTACTIVECALL   0
167 #define ACTIVECALL      1
168
169 #define CREATE_SGUID_ADMIN_ONLY 1
170
171 extern struct afsconf_dir *confDir;
172 extern afs_int32 dataVersionHigh;
173
174 extern int SystemId;
175 static struct AFSCallStatistics AFSCallStats;
176 #if FS_STATS_DETAILED
177 struct fs_stats_FullPerfStats afs_FullPerfStats;
178 extern int AnonymousID;
179 #endif /* FS_STATS_DETAILED */
180 #if OPENAFS_VOL_STATS
181 static const char nullString[] = "";
182 #endif /* OPENAFS_VOL_STATS */
183
184 struct afs_FSStats {
185     afs_int32 NothingYet;
186 };
187
188 struct afs_FSStats afs_fsstats;
189
190 int LogLevel = 0;
191 int supported = 1;
192 int Console = 0;
193 afs_int32 BlocksSpare = 1024;   /* allow 1 MB overruns */
194 afs_int32 PctSpare;
195 extern afs_int32 implicitAdminRights;
196 extern afs_int32 readonlyServer;
197 extern int CopyOnWrite_calls, CopyOnWrite_off0, CopyOnWrite_size0;
198 extern afs_fsize_t CopyOnWrite_maxsize;
199
200 /*
201  * Externals used by the xstat code.
202  */
203 extern VolPkgStats VStats;
204 extern int CEs, CEBlocks;
205
206 extern int HTs, HTBlocks;
207
208 afs_int32 FetchData_RXStyle(Volume * volptr, Vnode * targetptr,
209                             register struct rx_call *Call, afs_sfsize_t Pos,
210                             afs_sfsize_t Len, afs_int32 Int64Mode,
211 #if FS_STATS_DETAILED
212                             afs_sfsize_t * a_bytesToFetchP,
213                             afs_sfsize_t * a_bytesFetchedP
214 #endif                          /* FS_STATS_DETAILED */
215     );
216
217 afs_int32 StoreData_RXStyle(Volume * volptr, Vnode * targetptr,
218                             struct AFSFid *Fid, struct client *client,
219                             register struct rx_call *Call, afs_fsize_t Pos,
220                             afs_fsize_t Length, afs_fsize_t FileLength,
221                             int sync,
222 #if FS_STATS_DETAILED
223                             afs_sfsize_t * a_bytesToStoreP,
224                             afs_sfsize_t * a_bytesStoredP
225 #endif                          /* FS_STATS_DETAILED */
226     );
227
228 #ifdef AFS_SGI_XFS_IOPS_ENV
229 #include <afs/xfsattrs.h>
230 static int
231 GetLinkCount(Volume * avp, struct stat *astat)
232 {
233     if (!strcmp("xfs", astat->st_fstype)) {
234         return (astat->st_mode & AFS_XFS_MODE_LINK_MASK);
235     } else
236         return astat->st_nlink;
237 }
238 #else
239 #define GetLinkCount(V, S) (S)->st_nlink
240 #endif
241
242 afs_int32
243 SpareComp(Volume * avolp)
244 {
245     register afs_int32 temp;
246
247     FS_LOCK;
248     if (PctSpare) {
249         temp = V_maxquota(avolp);
250         if (temp == 0) {
251             /* no matter; doesn't check in this case */
252             FS_UNLOCK;
253             return 0;
254         }
255         temp = (temp * PctSpare) / 100;
256         FS_UNLOCK;
257         return temp;
258     } else {
259         FS_UNLOCK;
260         return BlocksSpare;
261     }
262
263 }                               /*SpareComp */
264
265 /*
266  * Set the volume synchronization parameter for this volume.  If it changes,
267  * the Cache Manager knows that the volume must be purged from the stat cache.
268  */
269 static void
270 SetVolumeSync(register struct AFSVolSync *async, register Volume * avol)
271 {
272     FS_LOCK;
273     /* date volume instance was created */
274     if (async) {
275         if (avol)
276             async->spare1 = avol->header->diskstuff.creationDate;
277         else
278             async->spare1 = 0;
279         async->spare2 = 0;
280         async->spare3 = 0;
281         async->spare4 = 0;
282         async->spare5 = 0;
283         async->spare6 = 0;
284     }
285     FS_UNLOCK;
286 }                               /*SetVolumeSync */
287
288 /*
289  * Note that this function always returns a held host, so
290  * that CallPostamble can block without the host's disappearing.
291  * Call returns rx connection in passed in *tconn
292  */
293 static int
294 CallPreamble(register struct rx_call *acall, int activecall,
295              struct rx_connection **tconn, struct host **ahostp)
296 {
297     struct host *thost;
298     struct client *tclient;
299     int retry_flag = 1;
300     int code = 0;
301     char hoststr[16], hoststr2[16];
302 #ifdef AFS_PTHREAD_ENV
303     struct ubik_client *uclient;
304 #endif
305     *ahostp = NULL;
306
307     if (!tconn) {
308         ViceLog(0, ("CallPreamble: unexpected null tconn!\n"));
309         return -1;
310     }
311     *tconn = rx_ConnectionOf(acall);
312
313     H_LOCK;
314   retry:
315     tclient = h_FindClient_r(*tconn);
316     if (!tclient) {
317         ViceLog(0, ("CallPreamble: Couldn't get CPS. Too many lockers\n"));
318         H_UNLOCK;
319         return VBUSY;
320     }
321     thost = tclient->host;
322     if (tclient->prfail == 1) { /* couldn't get the CPS */
323         if (!retry_flag) {
324             h_ReleaseClient_r(tclient);
325             h_Release_r(thost);
326             ViceLog(0, ("CallPreamble: Couldn't get CPS. Fail\n"));
327             H_UNLOCK;
328             return -1001;
329         }
330         retry_flag = 0;         /* Retry once */
331
332         /* Take down the old connection and re-read the key file */
333         ViceLog(0,
334                 ("CallPreamble: Couldn't get CPS. Reconnect to ptserver\n"));
335 #ifdef AFS_PTHREAD_ENV
336         uclient = (struct ubik_client *)pthread_getspecific(viced_uclient_key);
337
338         /* Is it still necessary to drop this? We hit the net, we should... */
339         H_UNLOCK;
340         if (uclient) {
341             hpr_End(uclient);
342             uclient = NULL;
343         }
344         code = hpr_Initialize(&uclient);
345
346         if (!code)
347             assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
348         H_LOCK;
349 #else
350         code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
351 #endif
352         if (code) {
353             h_ReleaseClient_r(tclient);
354             h_Release_r(thost);
355             H_UNLOCK;
356             ViceLog(0, ("CallPreamble: couldn't reconnect to ptserver\n"));
357             return -1001;
358         }
359
360         tclient->prfail = 2;    /* Means re-eval client's cps */
361         h_ReleaseClient_r(tclient);
362         h_Release_r(thost);
363         goto retry;
364     }
365
366     tclient->LastCall = thost->LastCall = FT_ApproxTime();
367     if (activecall)             /* For all but "GetTime", "GetStats", and "GetCaps" calls */
368         thost->ActiveCall = thost->LastCall;
369
370     h_Lock_r(thost);
371     if (thost->hostFlags & HOSTDELETED) {
372         ViceLog(3,
373                 ("Discarded a packet for deleted host %s:%d\n",
374                  afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port)));
375         code = VBUSY;           /* raced, so retry */
376     } else if ((thost->hostFlags & VENUSDOWN)
377                || (thost->hostFlags & HFE_LATER)) {
378         if (BreakDelayedCallBacks_r(thost)) {
379             ViceLog(0,
380                     ("BreakDelayedCallbacks FAILED for host %s:%d which IS UP.  Connection from %s:%d.  Possible network or routing failure.\n",
381                      afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port), afs_inet_ntoa_r(rxr_HostOf(*tconn), hoststr2), 
382                      ntohs(rxr_PortOf(*tconn))));
383             if (MultiProbeAlternateAddress_r(thost)) {
384                 ViceLog(0,
385                         ("MultiProbe failed to find new address for host %s:%d\n",
386                          afs_inet_ntoa_r(thost->host, hoststr),
387                          ntohs(thost->port)));
388                 code = -1;
389             } else {
390                 ViceLog(0,
391                         ("MultiProbe found new address for host %s:%d\n",
392                          afs_inet_ntoa_r(thost->host, hoststr),
393                          ntohs(thost->port)));
394                 if (BreakDelayedCallBacks_r(thost)) {
395                     ViceLog(0,
396                             ("BreakDelayedCallbacks FAILED AGAIN for host %s:%d which IS UP.  Connection from %s:%d.  Possible network or routing failure.\n",
397                               afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port), afs_inet_ntoa_r(rxr_HostOf(*tconn), hoststr2), 
398                               ntohs(rxr_PortOf(*tconn))));
399                     code = -1;
400                 }
401             }
402         }
403     } else {
404         code = 0;
405     }
406
407     h_ReleaseClient_r(tclient);
408     h_Unlock_r(thost);
409     H_UNLOCK;
410     *ahostp = thost;
411     return code;
412
413 }                               /*CallPreamble */
414
415
416 static afs_int32
417 CallPostamble(register struct rx_connection *aconn, afs_int32 ret,
418               struct host *ahost)
419 {
420     struct host *thost;
421     struct client *tclient;
422     int translate = 0;
423
424     H_LOCK;
425     tclient = h_FindClient_r(aconn);
426     if (!tclient) 
427         goto busyout;
428     thost = tclient->host;
429     if (thost->hostFlags & HERRORTRANS)
430         translate = 1;
431     h_ReleaseClient_r(tclient);
432
433     if (ahost) {
434             if (ahost != thost) {
435                     /* host/client recycle */
436                     char hoststr[16], hoststr2[16];
437                     ViceLog(0, ("CallPostamble: ahost %s:%d (%p) != thost "
438                                 "%s:%d (%p)\n",
439                                 afs_inet_ntoa_r(ahost->host, hoststr),
440                                 ntohs(ahost->port),
441                                 ahost,
442                                 afs_inet_ntoa_r(thost->host, hoststr2),
443                                 ntohs(thost->port),
444                                 thost));
445             }
446             /* return the reference taken in CallPreamble */
447             h_Release_r(ahost);
448     } else {
449             char hoststr[16];
450             ViceLog(0, ("CallPostamble: null ahost for thost %s:%d (%p)\n",
451                         afs_inet_ntoa_r(thost->host, hoststr),
452                         ntohs(thost->port),
453                         thost));
454     }
455
456     /* return the reference taken in local h_FindClient_r--h_ReleaseClient_r
457      * does not decrement refcount on client->host */
458     h_Release_r(thost);
459
460  busyout:
461     H_UNLOCK;
462     return (translate ? sys_error_to_et(ret) : ret);
463 }                               /*CallPostamble */
464
465 /*
466  * Returns the volume and vnode pointers associated with file Fid; the lock
467  * type on the vnode is set to lock. Note that both volume/vnode's ref counts
468  * are incremented and they must be eventualy released.
469  */
470 static afs_int32
471 CheckVnode(AFSFid * fid, Volume ** volptr, Vnode ** vptr, int lock)
472 {
473     Error fileCode = 0;
474     Error local_errorCode, errorCode = -1;
475     static struct timeval restartedat = { 0, 0 };
476
477     if (fid->Volume == 0 || fid->Vnode == 0)    /* not: || fid->Unique == 0) */
478         return (EINVAL);
479     if ((*volptr) == 0) {
480         extern int VInit;
481
482         while (1) {
483             int restarting = 
484 #ifdef AFS_DEMAND_ATTACH_FS
485                 VSALVAGE
486 #else
487                 VRESTARTING
488 #endif
489                 ;
490
491             errorCode = 0;
492             *volptr = VGetVolume(&local_errorCode, &errorCode, (afs_int32) fid->Volume);
493             if (!errorCode) {
494                 assert(*volptr);
495                 break;
496             }
497             if ((errorCode == VOFFLINE) && (VInit < 2)) {
498                 /* The volume we want may not be attached yet because
499                  * the volume initialization is not yet complete.
500                  * We can do several things: 
501                  *     1.  return -1, which will cause users to see
502                  *         "connection timed out".  This is more or
503                  *         less the same as always, except that the servers
504                  *         may appear to bounce up and down while they
505                  *         are actually restarting.
506                  *     2.  return VBUSY which will cause clients to 
507                  *         sleep and retry for 6.5 - 15 minutes, depending
508                  *         on what version of the CM they are running.  If
509                  *         the file server takes longer than that interval 
510                  *         to attach the desired volume, then the application
511                  *         will see an ENODEV or EIO.  This approach has 
512                  *         the advantage that volumes which have been attached
513                  *         are immediately available, it keeps the server's
514                  *         immediate backlog low, and the call is interruptible
515                  *         by the user.  Users see "waiting for busy volume."
516                  *     3.  sleep here and retry.  Some people like this approach
517                  *         because there is no danger of seeing errors.  However, 
518                  *         this approach only works with a bounded number of 
519                  *         clients, since the pending queues will grow without
520                  *         stopping.  It might be better to find a way to take
521                  *         this call and stick it back on a queue in order to
522                  *         recycle this thread for a different request.    
523                  *     4.  Return a new error code, which new cache managers will
524                  *         know enough to interpret as "sleep and retry", without
525                  *         the upper bound of 6-15 minutes that is imposed by the
526                  *         VBUSY handling.  Users will see "waiting for
527                  *         busy volume," so they know that something is
528                  *         happening.  Old cache managers must be able to do  
529                  *         something reasonable with this, for instance, mark the
530                  *         server down.  Fortunately, any error code < 0
531                  *         will elicit that behavior. See #1.
532                  *     5.  Some combination of the above.  I like doing #2 for 10
533                  *         minutes, followed by #4.  3.1b and 3.2 cache managers
534                  *         will be fine as long as the restart period is
535                  *         not longer than 6.5 minutes, otherwise they may
536                  *         return ENODEV to users.  3.3 cache managers will be
537                  *         fine for 10 minutes, then will return
538                  *         ETIMEDOUT.  3.4 cache managers will just wait
539                  *         until the call works or fails definitively.
540                  *  NB. The problem with 2,3,4,5 is that old clients won't
541                  *  fail over to an alternate read-only replica while this
542                  *  server is restarting.  3.4 clients will fail over right away.
543                  */
544                 if (restartedat.tv_sec == 0) {
545                     /* I'm not really worried about when we restarted, I'm   */
546                     /* just worried about when the first VBUSY was returned. */
547                     FT_GetTimeOfDay(&restartedat, 0);
548                     if (busyonrst) {
549                         FS_LOCK;
550                         afs_perfstats.fs_nBusies++;
551                         FS_UNLOCK;
552                     }
553                     return (busyonrst ? VBUSY : restarting);
554                 } else {
555                     struct timeval now;
556                     FT_GetTimeOfDay(&now, 0);
557                     if ((now.tv_sec - restartedat.tv_sec) < (11 * 60)) {
558                         if (busyonrst) {
559                             FS_LOCK;
560                             afs_perfstats.fs_nBusies++;
561                             FS_UNLOCK;
562                         }
563                         return (busyonrst ? VBUSY : restarting);
564                     } else {
565                         return (restarting);
566                     }
567                 }
568             }
569             /* allow read operations on busy volume. 
570              * must check local_errorCode because demand attach fs
571              * can have local_errorCode == VSALVAGING, errorCode == VBUSY */
572             else if (local_errorCode == VBUSY && lock == READ_LOCK) {
573 #ifdef AFS_DEMAND_ATTACH_FS
574                 /* DAFS case is complicated by the fact that local_errorCode can
575                  * be VBUSY in cases where the volume is truly offline */
576                 if (!*volptr) {
577                     /* volume is in VOL_STATE_UNATTACHED */
578                     return (errorCode);
579                 }
580 #endif /* AFS_DEMAND_ATTACH_FS */
581                 errorCode = 0;
582                 break;
583             } else if (errorCode)
584                 return (errorCode);
585         }
586     }
587     assert(*volptr);
588
589     /* get the vnode  */
590     *vptr = VGetVnode(&errorCode, *volptr, fid->Vnode, lock);
591     if (errorCode)
592         return (errorCode);
593     if ((*vptr)->disk.uniquifier != fid->Unique) {
594         VPutVnode(&fileCode, *vptr);
595         assert(fileCode == 0);
596         *vptr = 0;
597         return (VNOVNODE);      /* return the right error code, at least */
598     }
599     return (0);
600 }                               /*CheckVnode */
601
602 /*
603  * This routine returns the ACL associated with the targetptr. If the
604  * targetptr isn't a directory, we access its parent dir and get the ACL
605  * thru the parent; in such case the parent's vnode is returned in
606  * READ_LOCK mode.
607  */
608 static afs_int32
609 SetAccessList(Vnode ** targetptr, Volume ** volume,
610               struct acl_accessList **ACL, int *ACLSize, Vnode ** parent,
611               AFSFid * Fid, int Lock)
612 {
613     if ((*targetptr)->disk.type == vDirectory) {
614         *parent = 0;
615         *ACL = VVnodeACL(*targetptr);
616         *ACLSize = VAclSize(*targetptr);
617         return (0);
618     } else {
619         assert(Fid != 0);
620         while (1) {
621             VnodeId parentvnode;
622             Error errorCode = 0;
623
624             parentvnode = (*targetptr)->disk.parent;
625             VPutVnode(&errorCode, *targetptr);
626             *targetptr = 0;
627             if (errorCode)
628                 return (errorCode);
629             *parent = VGetVnode(&errorCode, *volume, parentvnode, READ_LOCK);
630             if (errorCode)
631                 return (errorCode);
632             *ACL = VVnodeACL(*parent);
633             *ACLSize = VAclSize(*parent);
634             if ((errorCode = CheckVnode(Fid, volume, targetptr, Lock)) != 0)
635                 return (errorCode);
636             if ((*targetptr)->disk.parent != parentvnode) {
637                 VPutVnode(&errorCode, *parent);
638                 *parent = 0;
639                 if (errorCode)
640                     return (errorCode);
641             } else
642                 return (0);
643         }
644     }
645
646 }                               /*SetAccessList */
647
648 /* Must not be called with H_LOCK held */
649 static void
650 client_CheckRights(struct client *client, struct acl_accessList *ACL, 
651                    afs_int32 *rights)
652 {
653     *rights = 0;
654     ObtainReadLock(&client->lock);
655     if (client->CPS.prlist_len > 0 && !client->deleted &&
656         client->host && !(client->host->hostFlags & HOSTDELETED))
657         acl_CheckRights(ACL, &client->CPS, rights);
658     ReleaseReadLock(&client->lock);
659 }
660
661 /* Must not be called with H_LOCK held */
662 static afs_int32
663 client_HasAsMember(struct client *client, afs_int32 id)
664 {
665     afs_int32 code = 0;
666
667     ObtainReadLock(&client->lock);
668     if (client->CPS.prlist_len > 0 && !client->deleted && 
669         client->host && !(client->host->hostFlags & HOSTDELETED))
670         code = acl_IsAMember(id, &client->CPS);
671     ReleaseReadLock(&client->lock);
672     return code;
673 }
674
675 /*
676  * Compare the directory's ACL with the user's access rights in the client
677  * connection and return the user's and everybody else's access permissions
678  * in rights and anyrights, respectively
679  */
680 static afs_int32
681 GetRights(struct client *client, struct acl_accessList *ACL,
682           afs_int32 * rights, afs_int32 * anyrights)
683 {
684     extern prlist SystemAnyUserCPS;
685     afs_int32 hrights = 0;
686 #ifndef AFS_PTHREAD_ENV
687     int code;
688 #endif
689
690     if (acl_CheckRights(ACL, &SystemAnyUserCPS, anyrights) != 0) {
691         ViceLog(0, ("CheckRights failed\n"));
692         *anyrights = 0;
693     }
694     *rights = 0;
695
696     client_CheckRights(client, ACL, rights);
697
698     /* wait if somebody else is already doing the getCPS call */
699     H_LOCK;
700     while (client->host->hostFlags & HCPS_INPROGRESS) {
701         client->host->hostFlags |= HCPS_WAITING;        /* I am waiting */
702 #ifdef AFS_PTHREAD_ENV
703         pthread_cond_wait(&client->host->cond, &host_glock_mutex);
704 #else /* AFS_PTHREAD_ENV */
705         if ((code =
706              LWP_WaitProcess(&(client->host->hostFlags))) != LWP_SUCCESS)
707             ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
708 #endif /* AFS_PTHREAD_ENV */
709     }
710
711     if (!client->host->hcps.prlist_len || !client->host->hcps.prlist_val) {
712         char hoststr[16];
713         ViceLog(5,
714                 ("CheckRights: len=%u, for host=%s:%d\n",
715                  client->host->hcps.prlist_len, 
716                  afs_inet_ntoa_r(client->host->host, hoststr),
717                  ntohs(client->host->port)));
718     } else
719         acl_CheckRights(ACL, &client->host->hcps, &hrights);
720     H_UNLOCK;
721     /* Allow system:admin the rights given with the -implicit option */
722     if (client_HasAsMember(client, SystemId))
723         *rights |= implicitAdminRights;
724
725     *rights |= hrights;
726     *anyrights |= hrights;
727
728     return (0);
729
730 }                               /*GetRights */
731
732 /*
733  * VanillaUser returns 1 (true) if the user is a vanilla user (i.e., not
734  * a System:Administrator)
735  */
736 static afs_int32
737 VanillaUser(struct client *client)
738 {
739     if (client_HasAsMember(client, SystemId))
740         return (0);             /* not a system administrator, then you're "vanilla" */
741     return (1);
742
743 }                               /*VanillaUser */
744
745
746 /*
747  * This unusual afs_int32-parameter routine encapsulates all volume package related
748  * operations together in a single function; it's called by almost all AFS
749  * interface calls.
750  */
751 static afs_int32
752 GetVolumePackage(struct rx_connection *tcon, AFSFid * Fid, Volume ** volptr,
753                  Vnode ** targetptr, int chkforDir, Vnode ** parent,
754                  struct client **client, int locktype, afs_int32 * rights,
755                  afs_int32 * anyrights)
756 {
757     struct acl_accessList *aCL; /* Internal access List */
758     int aCLSize;                /* size of the access list */
759     Error errorCode = 0;                /* return code to caller */
760
761     if ((errorCode = CheckVnode(Fid, volptr, targetptr, locktype)))
762         return (errorCode);
763     if (chkforDir) {
764         if (chkforDir == MustNOTBeDIR
765             && ((*targetptr)->disk.type == vDirectory))
766             return (EISDIR);
767         else if (chkforDir == MustBeDIR
768                  && ((*targetptr)->disk.type != vDirectory))
769             return (ENOTDIR);
770     }
771     if ((errorCode =
772          SetAccessList(targetptr, volptr, &aCL, &aCLSize, parent,
773                        (chkforDir == MustBeDIR ? (AFSFid *) 0 : Fid),
774                        (chkforDir == MustBeDIR ? 0 : locktype))) != 0)
775         return (errorCode);
776     if (chkforDir == MustBeDIR)
777         assert((*parent) == 0);
778     if (!(*client)) {
779         if ((errorCode = GetClient(tcon, client)) != 0)
780             return (errorCode);
781         if (!(*client))
782             return (EINVAL);
783     }
784     GetRights(*client, aCL, rights, anyrights);
785     /* ok, if this is not a dir, set the PRSFS_ADMINISTER bit iff we're the owner */
786     if ((*targetptr)->disk.type != vDirectory) {
787         /* anyuser can't be owner, so only have to worry about rights, not anyrights */
788         if ((*targetptr)->disk.owner == (*client)->ViceId)
789             (*rights) |= PRSFS_ADMINISTER;
790         else
791             (*rights) &= ~PRSFS_ADMINISTER;
792     }
793 #ifdef ADMIN_IMPLICIT_LOOKUP
794     /* admins get automatic lookup on everything */
795     if (!VanillaUser(*client))
796         (*rights) |= PRSFS_LOOKUP;
797 #endif /* ADMIN_IMPLICIT_LOOKUP */
798     return errorCode;
799
800 }                               /*GetVolumePackage */
801
802
803 /*
804  * This is the opposite of GetVolumePackage(), and is always used at the end of
805  * AFS calls to put back all used vnodes and the volume in the proper order!
806  */
807 static void
808 PutVolumePackage(Vnode * parentwhentargetnotdir, Vnode * targetptr,
809                  Vnode * parentptr, Volume * volptr, struct client **client)
810 {
811     Error fileCode = 0;         /* Error code returned by the volume package */
812
813     if (parentwhentargetnotdir) {
814         VPutVnode(&fileCode, parentwhentargetnotdir);
815         assert(!fileCode || (fileCode == VSALVAGE));
816     }
817     if (targetptr) {
818         VPutVnode(&fileCode, targetptr);
819         assert(!fileCode || (fileCode == VSALVAGE));
820     }
821     if (parentptr) {
822         VPutVnode(&fileCode, parentptr);
823         assert(!fileCode || (fileCode == VSALVAGE));
824     }
825     if (volptr) {
826         VPutVolume(volptr);
827     }
828     if (*client) {
829         PutClient(client);
830     }
831 }                               /*PutVolumePackage */
832
833 static int
834 VolumeOwner(register struct client *client, register Vnode * targetptr)
835 {
836     afs_int32 owner = V_owner(targetptr->volumePtr);    /* get volume owner */
837
838     if (owner >= 0)
839         return (client->ViceId == owner);
840     else {
841         /* 
842          * We don't have to check for host's cps since only regular
843          * viceid are volume owners.
844          */
845         return (client_HasAsMember(client, owner));
846     }
847
848 }                               /*VolumeOwner */
849
850 static int
851 VolumeRootVnode(Vnode * targetptr)
852 {
853     return ((targetptr->vnodeNumber == ROOTVNODE)
854             && (targetptr->disk.uniquifier == 1));
855
856 }                               /*VolumeRootVnode */
857
858 /*
859  * Check if target file has the proper access permissions for the Fetch
860  * (FetchData, FetchACL, FetchStatus) and Store (StoreData, StoreACL,
861  * StoreStatus) related calls
862  */
863 /* this code should probably just set a "priv" flag where all the audit events
864  * are now, and only generate the audit event once at the end of the routine, 
865  * thus only generating the event if all the checks succeed, but only because
866  * of the privilege       XXX
867  */
868 static afs_int32
869 Check_PermissionRights(Vnode * targetptr, struct client *client,
870                        afs_int32 rights, int CallingRoutine,
871                        AFSStoreStatus * InStatus)
872 {
873     Error errorCode = 0;
874 #define OWNSp(client, target) ((client)->ViceId == (target)->disk.owner)
875 #define CHOWN(i,t) (((i)->Mask & AFS_SETOWNER) &&((i)->Owner != (t)->disk.owner))
876 #define CHGRP(i,t) (((i)->Mask & AFS_SETGROUP) &&((i)->Group != (t)->disk.group))
877
878     if (CallingRoutine & CHK_FETCH) {
879         if (CallingRoutine == CHK_FETCHDATA || VanillaUser(client)) {
880             if (targetptr->disk.type == vDirectory
881                 || targetptr->disk.type == vSymlink) {
882                 if (!(rights & PRSFS_LOOKUP)
883 #ifdef ADMIN_IMPLICIT_LOOKUP
884                     /* grant admins fetch on all directories */
885                     && VanillaUser(client)
886 #endif /* ADMIN_IMPLICIT_LOOKUP */
887                     && !VolumeOwner(client, targetptr))
888                     return (EACCES);
889             } else {            /* file */
890                 /* must have read access, or be owner and have insert access */
891                 if (!(rights & PRSFS_READ)
892                     && !(OWNSp(client, targetptr) && (rights & PRSFS_INSERT)))
893                     return (EACCES);
894             }
895             if (CallingRoutine == CHK_FETCHDATA
896                 && targetptr->disk.type == vFile)
897 #ifdef USE_GROUP_PERMS
898                 if (!OWNSp(client, targetptr)
899                     && !client_HasAsMember(client, targetptr->disk.owner)) {
900                     errorCode =
901                         (((GROUPREAD | GROUPEXEC) & targetptr->disk.modeBits)
902                          ? 0 : EACCES);
903                 } else {
904                     errorCode =
905                         (((OWNERREAD | OWNEREXEC) & targetptr->disk.modeBits)
906                          ? 0 : EACCES);
907                 }
908 #else
909                 /*
910                  * The check with the ownership below is a kludge to allow
911                  * reading of files created with no read permission. The owner
912                  * of the file is always allowed to read it.
913                  */
914                 if ((client->ViceId != targetptr->disk.owner)
915                     && VanillaUser(client))
916                     errorCode =
917                         (((OWNERREAD | OWNEREXEC) & targetptr->disk.
918                           modeBits) ? 0 : EACCES);
919 #endif
920         } else {                /*  !VanillaUser(client) && !FetchData */
921
922             osi_audit(PrivilegeEvent, 0, AUD_ID,
923                       (client ? client->ViceId : 0), AUD_INT, CallingRoutine,
924                       AUD_END);
925         }
926     } else {                    /* a store operation */
927         if ((rights & PRSFS_INSERT) && OWNSp(client, targetptr)
928             && (CallingRoutine != CHK_STOREACL)
929             && (targetptr->disk.type == vFile)) {
930             /* bypass protection checks on first store after a create
931              * for the creator; also prevent chowns during this time
932              * unless you are a system administrator */
933           /******  InStatus->Owner && UnixModeBits better be SET!! */
934             if (CHOWN(InStatus, targetptr) || CHGRP(InStatus, targetptr)) {
935                 if (readonlyServer)
936                     return (VREADONLY);
937                 else if (VanillaUser(client))
938                     return (EPERM);     /* Was EACCES */
939                 else
940                     osi_audit(PrivilegeEvent, 0, AUD_ID,
941                               (client ? client->ViceId : 0), AUD_INT,
942                               CallingRoutine, AUD_END);
943             }
944         } else {
945             if (CallingRoutine != CHK_STOREDATA && !VanillaUser(client)) {
946                 osi_audit(PrivilegeEvent, 0, AUD_ID,
947                           (client ? client->ViceId : 0), AUD_INT,
948                           CallingRoutine, AUD_END);
949             } else {
950                 if (readonlyServer) {
951                     return (VREADONLY);
952                 }
953                 if (CallingRoutine == CHK_STOREACL) {
954                     if (!(rights & PRSFS_ADMINISTER)
955                         && !VolumeOwner(client, targetptr))
956                         return (EACCES);
957                 } else {        /* store data or status */
958                     /* watch for chowns and chgrps */
959                     if (CHOWN(InStatus, targetptr)
960                         || CHGRP(InStatus, targetptr)) {
961                         if (readonlyServer)
962                             return (VREADONLY);
963                         else if (VanillaUser(client))
964                             return (EPERM);     /* Was EACCES */
965                         else
966                             osi_audit(PrivilegeEvent, 0, AUD_ID,
967                                       (client ? client->ViceId : 0), AUD_INT,
968                                       CallingRoutine, AUD_END);
969                     }
970                     /* must be sysadmin to set suid/sgid bits */
971                     if ((InStatus->Mask & AFS_SETMODE) &&
972 #ifdef AFS_NT40_ENV
973                         (InStatus->UnixModeBits & 0xc00) != 0) {
974 #else
975                         (InStatus->UnixModeBits & (S_ISUID | S_ISGID)) != 0) {
976 #endif
977                         if (readonlyServer)
978                             return (VREADONLY);
979                         if (VanillaUser(client))
980                             return (EACCES);
981                         else
982                             osi_audit(PrivSetID, 0, AUD_ID,
983                                       (client ? client->ViceId : 0), AUD_INT,
984                                       CallingRoutine, AUD_END);
985                     }
986                     if (CallingRoutine == CHK_STOREDATA) {
987                         if (readonlyServer)
988                             return (VREADONLY);
989                         if (!(rights & PRSFS_WRITE))
990                             return (EACCES);
991                         /* Next thing is tricky.  We want to prevent people
992                          * from writing files sans 0200 bit, but we want
993                          * creating new files with 0444 mode to work.  We
994                          * don't check the 0200 bit in the "you are the owner"
995                          * path above, but here we check the bit.  However, if
996                          * you're a system administrator, we ignore the 0200
997                          * bit anyway, since you may have fchowned the file,
998                          * too */
999 #ifdef USE_GROUP_PERMS
1000                         if ((targetptr->disk.type == vFile)
1001                             && VanillaUser(client)) {
1002                             if (!OWNSp(client, targetptr)
1003                                 && !client_HasAsMember(client, targetptr->disk.owner)) {
1004                                 errorCode =
1005                                     ((GROUPWRITE & targetptr->disk.modeBits)
1006                                      ? 0 : EACCES);
1007                             } else {
1008                                 errorCode =
1009                                     ((OWNERWRITE & targetptr->disk.modeBits)
1010                                      ? 0 : EACCES);
1011                             }
1012                         } else
1013 #endif
1014                             if ((targetptr->disk.type != vDirectory)
1015                                 && (!(targetptr->disk.modeBits & OWNERWRITE))) {
1016                             if (readonlyServer)
1017                                 return (VREADONLY);
1018                             if (VanillaUser(client))
1019                                 return (EACCES);
1020                             else
1021                                 osi_audit(PrivilegeEvent, 0, AUD_ID,
1022                                           (client ? client->ViceId : 0),
1023                                           AUD_INT, CallingRoutine, AUD_END);
1024                         }
1025                     } else {    /* a status store */
1026                         if (readonlyServer)
1027                             return (VREADONLY);
1028                         if (targetptr->disk.type == vDirectory) {
1029                             if (!(rights & PRSFS_DELETE)
1030                                 && !(rights & PRSFS_INSERT))
1031                                 return (EACCES);
1032                         } else {        /* a file  or symlink */
1033                             if (!(rights & PRSFS_WRITE))
1034                                 return (EACCES);
1035                         }
1036                     }
1037                 }
1038             }
1039         }
1040     }
1041     return (errorCode);
1042
1043 }                               /*Check_PermissionRights */
1044
1045
1046 /*
1047  * The Access List information is converted from its internal form in the
1048  * target's vnode buffer (or its parent vnode buffer if not a dir), to an
1049  * external form and returned back to the caller, via the AccessList
1050  * structure
1051  */
1052 static afs_int32
1053 RXFetch_AccessList(Vnode * targetptr, Vnode * parentwhentargetnotdir,
1054                    struct AFSOpaque *AccessList)
1055 {
1056     char *eACL;                 /* External access list placeholder */
1057
1058     if (acl_Externalize_pr
1059         (hpr_IdToName, (targetptr->disk.type ==
1060           vDirectory ? VVnodeACL(targetptr) :
1061           VVnodeACL(parentwhentargetnotdir)), &eACL) != 0) {
1062         return EIO;
1063     }
1064     if ((strlen(eACL) + 1) > AFSOPAQUEMAX) {
1065         acl_FreeExternalACL(&eACL);
1066         return (E2BIG);
1067     } else {
1068         strcpy((char *)(AccessList->AFSOpaque_val), (char *)eACL);
1069         AccessList->AFSOpaque_len = strlen(eACL) + 1;
1070     }
1071     acl_FreeExternalACL(&eACL);
1072     return (0);
1073
1074 }                               /*RXFetch_AccessList */
1075
1076
1077 /*
1078  * The Access List information is converted from its external form in the
1079  * input AccessList structure to the internal representation and copied into
1080  * the target dir's vnode storage.
1081  */
1082 static afs_int32
1083 RXStore_AccessList(Vnode * targetptr, struct AFSOpaque *AccessList)
1084 {
1085     struct acl_accessList *newACL;      /* PlaceHolder for new access list */
1086
1087     if (acl_Internalize_pr(hpr_NameToId, AccessList->AFSOpaque_val, &newACL)
1088         != 0)
1089         return (EINVAL);
1090     if ((newACL->size + 4) > VAclSize(targetptr))
1091         return (E2BIG);
1092     memcpy((char *)VVnodeACL(targetptr), (char *)newACL, (int)(newACL->size));
1093     acl_FreeACL(&newACL);
1094     return (0);
1095
1096 }                               /*RXStore_AccessList */
1097
1098
1099 /* In our current implementation, each successive data store (new file
1100  * data version) creates a new inode. This function creates the new
1101  * inode, copies the old inode's contents to the new one, remove the old
1102  * inode (i.e. decrement inode count -- if it's currently used the delete
1103  * will be delayed), and modify some fields (i.e. vnode's
1104  * disk.inodeNumber and cloned)
1105  */
1106 #define COPYBUFFSIZE    8192
1107 #define MAXFSIZE (~(afs_fsize_t) 0)
1108 static int
1109 CopyOnWrite(Vnode * targetptr, Volume * volptr, afs_fsize_t off, afs_fsize_t len)
1110 {
1111     Inode ino, nearInode;
1112     int rdlen;
1113     int wrlen;
1114     register afs_fsize_t size;
1115     register int length;
1116     char *buff;
1117     int rc;                     /* return code */
1118     IHandle_t *newH;            /* Use until finished copying, then cp to vnode. */
1119     FdHandle_t *targFdP;        /* Source Inode file handle */
1120     FdHandle_t *newFdP;         /* Dest Inode file handle */
1121
1122     if (targetptr->disk.type == vDirectory)
1123         DFlush();               /* just in case? */
1124
1125     VN_GET_LEN(size, targetptr);
1126     if (size > off) 
1127         size -= off;
1128     else 
1129         size = 0;
1130     if (size > len)
1131         size = len;
1132
1133     buff = (char *)malloc(COPYBUFFSIZE);
1134     if (buff == NULL) {
1135         return EIO;
1136     }
1137
1138     ino = VN_GET_INO(targetptr);
1139     if (!VALID_INO(ino)) {
1140         free(buff);
1141         VTakeOffline(volptr);
1142         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
1143                     volptr->hashid));
1144         return EIO;
1145     }    
1146     targFdP = IH_OPEN(targetptr->handle);
1147     if (targFdP == NULL) {
1148         rc = errno;
1149         ViceLog(0,
1150                 ("CopyOnWrite failed: Failed to open target vnode %u in volume %u (errno = %d)\n",
1151                  targetptr->vnodeNumber, V_id(volptr), rc));
1152         free(buff);
1153         VTakeOffline(volptr);
1154         return rc;
1155     }
1156
1157     nearInode = VN_GET_INO(targetptr);
1158     ino =
1159         IH_CREATE(V_linkHandle(volptr), V_device(volptr),
1160                   VPartitionPath(V_partition(volptr)), nearInode,
1161                   V_id(volptr), targetptr->vnodeNumber,
1162                   targetptr->disk.uniquifier,
1163                   (int)targetptr->disk.dataVersion);
1164     if (!VALID_INO(ino)) {
1165         ViceLog(0,
1166                 ("CopyOnWrite failed: Partition %s that contains volume %u may be out of free inodes(errno = %d)\n",
1167                  volptr->partition->name, V_id(volptr), errno));
1168         FDH_CLOSE(targFdP);
1169         free(buff);
1170         return ENOSPC;
1171     }
1172     IH_INIT(newH, V_device(volptr), V_id(volptr), ino);
1173     newFdP = IH_OPEN(newH);
1174     assert(newFdP != NULL);
1175
1176     FDH_SEEK(targFdP, off, SEEK_SET);
1177     FDH_SEEK(newFdP, off, SEEK_SET);
1178     while (size > 0) {
1179         if (size > COPYBUFFSIZE) {      /* more than a buffer */
1180             length = COPYBUFFSIZE;
1181             size -= COPYBUFFSIZE;
1182         } else {
1183             length = (int)size;
1184             size = 0;
1185         }
1186         rdlen = FDH_READ(targFdP, buff, length);
1187         if (rdlen == length)
1188             wrlen = FDH_WRITE(newFdP, buff, length);
1189         else
1190             wrlen = 0;
1191         /*  Callers of this function are not prepared to recover
1192          *  from error that put the filesystem in an inconsistent
1193          *  state. Make sure that we force the volume off-line if
1194          *  we some error other than ENOSPC - 4.29.99)
1195          *
1196          *  In case we are unable to write the required bytes, and the
1197          *  error code indicates that the disk is full, we roll-back to
1198          *  the initial state.
1199          */
1200         if ((rdlen != length) || (wrlen != length)) {
1201             if ((wrlen < 0) && (errno == ENOSPC)) {     /* disk full */
1202                 ViceLog(0,
1203                         ("CopyOnWrite failed: Partition %s containing volume %u is full\n",
1204                          volptr->partition->name, V_id(volptr)));
1205                 /* remove destination inode which was partially copied till now */
1206                 FDH_REALLYCLOSE(newFdP);
1207                 IH_RELEASE(newH);
1208                 FDH_REALLYCLOSE(targFdP);
1209                 rc = IH_DEC(V_linkHandle(volptr), ino, V_parentId(volptr));
1210                 if (!rc) {
1211                     ViceLog(0,
1212                             ("CopyOnWrite failed: error %u after i_dec on disk full, volume %u in partition %s needs salvage\n",
1213                              rc, V_id(volptr), volptr->partition->name));
1214                     VTakeOffline(volptr);
1215                 }
1216                 free(buff);
1217                 return ENOSPC;
1218             } else {
1219                 ViceLog(0,
1220                         ("CopyOnWrite failed: volume %u in partition %s  (tried reading %u, read %u, wrote %u, errno %u) volume needs salvage\n",
1221                          V_id(volptr), volptr->partition->name, length, rdlen,
1222                          wrlen, errno));
1223 #if defined(AFS_DEMAND_ATTACH_FS)
1224                 ViceLog(0, ("CopyOnWrite failed: requesting salvage\n"));
1225 #else
1226                 ViceLog(0, ("CopyOnWrite failed: taking volume offline\n"));
1227 #endif
1228                 /* Decrement this inode so salvager doesn't find it. */
1229                 FDH_REALLYCLOSE(newFdP);
1230                 IH_RELEASE(newH);
1231                 FDH_REALLYCLOSE(targFdP);
1232                 rc = IH_DEC(V_linkHandle(volptr), ino, V_parentId(volptr));
1233                 free(buff);
1234                 VTakeOffline(volptr);
1235                 return EIO;
1236             }
1237         }
1238 #ifndef AFS_PTHREAD_ENV
1239         IOMGR_Poll();
1240 #endif /* !AFS_PTHREAD_ENV */
1241     }
1242     FDH_REALLYCLOSE(targFdP);
1243     rc = IH_DEC(V_linkHandle(volptr), VN_GET_INO(targetptr),
1244                 V_parentId(volptr));
1245     assert(!rc);
1246     IH_RELEASE(targetptr->handle);
1247
1248     rc = FDH_SYNC(newFdP);
1249     assert(rc == 0);
1250     FDH_CLOSE(newFdP);
1251     targetptr->handle = newH;
1252     VN_SET_INO(targetptr, ino);
1253     targetptr->disk.cloned = 0;
1254     /* Internal change to vnode, no user level change to volume - def 5445 */
1255     targetptr->changed_oldTime = 1;
1256     free(buff);
1257     return 0;                   /* success */
1258 }                               /*CopyOnWrite */
1259
1260 static int
1261 CopyOnWrite2(FdHandle_t *targFdP, FdHandle_t *newFdP, afs_fsize_t off, afs_fsize_t size) {
1262     char *buff = (char *)malloc(COPYBUFFSIZE);
1263     register int length;
1264     int rdlen;
1265     int wrlen;
1266     int rc;
1267
1268     FDH_SEEK(targFdP, off, SEEK_SET);
1269     FDH_SEEK(newFdP, off, SEEK_SET);
1270
1271     if (size > FDH_SIZE(targFdP) - off) size = FDH_SIZE(targFdP) - off;
1272     while (size > 0) {
1273         if (size > COPYBUFFSIZE) {      /* more than a buffer */
1274             length = COPYBUFFSIZE;
1275             size -= COPYBUFFSIZE;
1276         } else {
1277             length = (int)size;
1278             size = 0;
1279         }
1280         rdlen = FDH_READ(targFdP, buff, length);
1281         if (rdlen == length)
1282             wrlen = FDH_WRITE(newFdP, buff, length);
1283         else
1284             wrlen = 0;
1285
1286         if ((rdlen != length) || (wrlen != length)) {
1287             /* no error recovery, at the worst we'll have a "hole" in the file */
1288             rc = 1;
1289             break;
1290         }
1291     }
1292     free(buff);
1293     return rc;
1294 }
1295
1296
1297 /*
1298  * Common code to handle with removing the Name (file when it's called from
1299  * SAFS_RemoveFile() or an empty dir when called from SAFS_rmdir()) from a
1300  * given directory, parentptr.
1301  */
1302 int DT1 = 0, DT0 = 0;
1303 static afs_int32
1304 DeleteTarget(Vnode * parentptr, Volume * volptr, Vnode ** targetptr,
1305              DirHandle * dir, AFSFid * fileFid, char *Name, int ChkForDir)
1306 {
1307     DirHandle childdir;         /* Handle for dir package I/O */
1308     Error errorCode = 0;
1309     int code;
1310
1311     /* watch for invalid names */
1312     if (!strcmp(Name, ".") || !strcmp(Name, ".."))
1313         return (EINVAL);
1314     if (parentptr->disk.cloned) {
1315         ViceLog(25, ("DeleteTarget : CopyOnWrite called\n"));
1316         if ((errorCode = CopyOnWrite(parentptr, volptr, 0, MAXFSIZE))) {
1317             ViceLog(20,
1318                     ("DeleteTarget %s: CopyOnWrite failed %d\n", Name,
1319                      errorCode));
1320             return errorCode;
1321         }
1322     }
1323
1324     /* check that the file is in the directory */
1325     SetDirHandle(dir, parentptr);
1326     if (Lookup(dir, Name, fileFid))
1327         return (ENOENT);
1328     fileFid->Volume = V_id(volptr);
1329
1330     /* just-in-case check for something causing deadlock */
1331     if (fileFid->Vnode == parentptr->vnodeNumber)
1332         return (EINVAL);
1333
1334     *targetptr = VGetVnode(&errorCode, volptr, fileFid->Vnode, WRITE_LOCK);
1335     if (errorCode) {
1336         return (errorCode);
1337     }
1338     if (ChkForDir == MustBeDIR) {
1339         if ((*targetptr)->disk.type != vDirectory)
1340             return (ENOTDIR);
1341     } else if ((*targetptr)->disk.type == vDirectory)
1342         return (EISDIR);
1343
1344     /*assert((*targetptr)->disk.uniquifier == fileFid->Unique); */
1345     /**
1346       * If the uniquifiers dont match then instead of asserting
1347       * take the volume offline and return VSALVAGE
1348       */
1349     if ((*targetptr)->disk.uniquifier != fileFid->Unique) {
1350         VTakeOffline(volptr);
1351         ViceLog(0,
1352                 ("Volume %u now offline, must be salvaged.\n",
1353                  volptr->hashid));
1354         errorCode = VSALVAGE;
1355         return errorCode;
1356     }
1357
1358     if (ChkForDir == MustBeDIR) {
1359         SetDirHandle(&childdir, *targetptr);
1360         if (IsEmpty(&childdir) != 0)
1361             return (EEXIST);
1362         DZap((afs_int32 *) &childdir);
1363         FidZap(&childdir);
1364         (*targetptr)->delete = 1;
1365     } else if ((--(*targetptr)->disk.linkCount) == 0)
1366         (*targetptr)->delete = 1;
1367     if ((*targetptr)->delete) {
1368         if (VN_GET_INO(*targetptr)) {
1369             DT0++;
1370             IH_REALLYCLOSE((*targetptr)->handle);
1371             errorCode =
1372                 IH_DEC(V_linkHandle(volptr), VN_GET_INO(*targetptr),
1373                        V_parentId(volptr));
1374             IH_RELEASE((*targetptr)->handle);
1375             if (errorCode == -1) {
1376                 ViceLog(0,
1377                         ("DT: inode=%s, name=%s, errno=%d\n",
1378                          PrintInode(NULL, VN_GET_INO(*targetptr)), Name,
1379                          errno));
1380                 if (errno != ENOENT)
1381                 {
1382                     VTakeOffline(volptr);
1383                     ViceLog(0,
1384                             ("Volume %u now offline, must be salvaged.\n",
1385                              volptr->hashid));
1386                     return (EIO);
1387                 }
1388                 DT1++;
1389                 errorCode = 0;
1390             }
1391         }
1392         VN_SET_INO(*targetptr, (Inode) 0);
1393         {
1394             afs_fsize_t adjLength;
1395             VN_GET_LEN(adjLength, *targetptr);
1396             VAdjustDiskUsage(&errorCode, volptr, -(int)nBlocks(adjLength), 0);
1397         }
1398     }
1399
1400     (*targetptr)->changed_newTime = 1;  /* Status change of deleted file/dir */
1401
1402     code = Delete(dir, (char *)Name);
1403     if (code) {
1404         ViceLog(0,
1405                 ("Error %d deleting %s\n", code,
1406                  (((*targetptr)->disk.type ==
1407                    Directory) ? "directory" : "file")));
1408         VTakeOffline(volptr);
1409         ViceLog(0,
1410                 ("Volume %u now offline, must be salvaged.\n",
1411                  volptr->hashid));
1412         if (!errorCode)
1413             errorCode = code;
1414     }
1415
1416     DFlush();
1417     return (errorCode);
1418
1419 }                               /*DeleteTarget */
1420
1421
1422 /*
1423  * This routine updates the parent directory's status block after the
1424  * specified operation (i.e. RemoveFile(), CreateFile(), Rename(),
1425  * SymLink(), Link(), MakeDir(), RemoveDir()) on one of its children has
1426  * been performed.
1427  */
1428 static void
1429 Update_ParentVnodeStatus(Vnode * parentptr, Volume * volptr, DirHandle * dir,
1430                          int author, int linkcount,
1431 #if FS_STATS_DETAILED
1432                          char a_inSameNetwork
1433 #endif                          /* FS_STATS_DETAILED */
1434     )
1435 {
1436     afs_fsize_t newlength;      /* Holds new directory length */
1437     afs_fsize_t parentLength;
1438     Error errorCode;
1439 #if FS_STATS_DETAILED
1440     Date currDate;              /*Current date */
1441     int writeIdx;               /*Write index to bump */
1442     int timeIdx;                /*Authorship time index to bump */
1443 #endif /* FS_STATS_DETAILED */
1444
1445     parentptr->disk.dataVersion++;
1446     newlength = (afs_fsize_t) Length(dir);
1447     /* 
1448      * This is a called on both dir removals (i.e. remove, removedir, rename) but also in dir additions
1449      * (create, symlink, link, makedir) so we need to check if we have enough space
1450      * XXX But we still don't check the error since we're dealing with dirs here and really the increase
1451      * of a new entry would be too tiny to worry about failures (since we have all the existing cushion)
1452      */
1453     VN_GET_LEN(parentLength, parentptr);
1454     if (nBlocks(newlength) != nBlocks(parentLength)) {
1455         VAdjustDiskUsage(&errorCode, volptr,
1456                          (nBlocks(newlength) - nBlocks(parentLength)),
1457                          (nBlocks(newlength) - nBlocks(parentLength)));
1458     }
1459     VN_SET_LEN(parentptr, newlength);
1460
1461 #if FS_STATS_DETAILED
1462     /*
1463      * Update directory write stats for this volume.  Note that the auth
1464      * counter is located immediately after its associated ``distance''
1465      * counter.
1466      */
1467     if (a_inSameNetwork)
1468         writeIdx = VOL_STATS_SAME_NET;
1469     else
1470         writeIdx = VOL_STATS_DIFF_NET;
1471     V_stat_writes(volptr, writeIdx)++;
1472     if (author != AnonymousID) {
1473         V_stat_writes(volptr, writeIdx + 1)++;
1474     }
1475
1476     /*
1477      * Update the volume's authorship information in response to this
1478      * directory operation.  Get the current time, decide to which time
1479      * slot this operation belongs, and bump the appropriate slot.
1480      */
1481     currDate = (FT_ApproxTime() - parentptr->disk.unixModifyTime);
1482     timeIdx =
1483         (currDate < VOL_STATS_TIME_CAP_0 ? VOL_STATS_TIME_IDX_0 : currDate <
1484          VOL_STATS_TIME_CAP_1 ? VOL_STATS_TIME_IDX_1 : currDate <
1485          VOL_STATS_TIME_CAP_2 ? VOL_STATS_TIME_IDX_2 : currDate <
1486          VOL_STATS_TIME_CAP_3 ? VOL_STATS_TIME_IDX_3 : currDate <
1487          VOL_STATS_TIME_CAP_4 ? VOL_STATS_TIME_IDX_4 : VOL_STATS_TIME_IDX_5);
1488     if (parentptr->disk.author == author) {
1489         V_stat_dirSameAuthor(volptr, timeIdx)++;
1490     } else {
1491         V_stat_dirDiffAuthor(volptr, timeIdx)++;
1492     }
1493 #endif /* FS_STATS_DETAILED */
1494
1495     parentptr->disk.author = author;
1496     parentptr->disk.linkCount = linkcount;
1497     parentptr->disk.unixModifyTime = FT_ApproxTime();   /* This should be set from CLIENT!! */
1498     parentptr->disk.serverModifyTime = FT_ApproxTime();
1499     parentptr->changed_newTime = 1;     /* vnode changed, write it back. */
1500 }
1501
1502
1503 /*
1504  * Update the target file's (or dir's) status block after the specified
1505  * operation is complete. Note that some other fields maybe updated by
1506  * the individual module.
1507  */
1508
1509 /* XXX INCOMPLETE - More attention is needed here! */
1510 static void
1511 Update_TargetVnodeStatus(Vnode * targetptr, afs_uint32 Caller,
1512                          struct client *client, AFSStoreStatus * InStatus,
1513                          Vnode * parentptr, Volume * volptr,
1514                          afs_fsize_t length)
1515 {
1516 #if FS_STATS_DETAILED
1517     Date currDate;              /*Current date */
1518     int writeIdx;               /*Write index to bump */
1519     int timeIdx;                /*Authorship time index to bump */
1520 #endif /* FS_STATS_DETAILED */
1521
1522     if (Caller & (TVS_CFILE | TVS_SLINK | TVS_MKDIR)) { /* initialize new file */
1523         targetptr->disk.parent = parentptr->vnodeNumber;
1524         VN_SET_LEN(targetptr, length);
1525         /* targetptr->disk.group =      0;  save some cycles */
1526         targetptr->disk.modeBits = 0777;
1527         targetptr->disk.owner = client->ViceId;
1528         targetptr->disk.dataVersion = 0;        /* consistent with the client */
1529         targetptr->disk.linkCount = (Caller & TVS_MKDIR ? 2 : 1);
1530         /* the inode was created in Alloc_NewVnode() */
1531     }
1532 #if FS_STATS_DETAILED
1533     /*
1534      * Update file write stats for this volume.  Note that the auth
1535      * counter is located immediately after its associated ``distance''
1536      * counter.
1537      */
1538     if (client->InSameNetwork)
1539         writeIdx = VOL_STATS_SAME_NET;
1540     else
1541         writeIdx = VOL_STATS_DIFF_NET;
1542     V_stat_writes(volptr, writeIdx)++;
1543     if (client->ViceId != AnonymousID) {
1544         V_stat_writes(volptr, writeIdx + 1)++;
1545     }
1546
1547     /*
1548      * We only count operations that DON'T involve creating new objects
1549      * (files, symlinks, directories) or simply setting status as
1550      * authorship-change operations.
1551      */
1552     if (!(Caller & (TVS_CFILE | TVS_SLINK | TVS_MKDIR | TVS_SSTATUS))) {
1553         /*
1554          * Update the volume's authorship information in response to this
1555          * file operation.  Get the current time, decide to which time
1556          * slot this operation belongs, and bump the appropriate slot.
1557          */
1558         currDate = (FT_ApproxTime() - targetptr->disk.unixModifyTime);
1559         timeIdx =
1560             (currDate <
1561              VOL_STATS_TIME_CAP_0 ? VOL_STATS_TIME_IDX_0 : currDate <
1562              VOL_STATS_TIME_CAP_1 ? VOL_STATS_TIME_IDX_1 : currDate <
1563              VOL_STATS_TIME_CAP_2 ? VOL_STATS_TIME_IDX_2 : currDate <
1564              VOL_STATS_TIME_CAP_3 ? VOL_STATS_TIME_IDX_3 : currDate <
1565              VOL_STATS_TIME_CAP_4 ? VOL_STATS_TIME_IDX_4 :
1566              VOL_STATS_TIME_IDX_5);
1567         if (targetptr->disk.author == client->ViceId) {
1568             V_stat_fileSameAuthor(volptr, timeIdx)++;
1569         } else {
1570             V_stat_fileDiffAuthor(volptr, timeIdx)++;
1571         }
1572     }
1573 #endif /* FS_STATS_DETAILED */
1574
1575     if (!(Caller & TVS_SSTATUS))
1576         targetptr->disk.author = client->ViceId;
1577     if (Caller & TVS_SDATA) {
1578         targetptr->disk.dataVersion++;
1579         if (VanillaUser(client)) {
1580             targetptr->disk.modeBits &= ~04000; /* turn off suid for file. */
1581 #ifdef CREATE_SGUID_ADMIN_ONLY
1582             targetptr->disk.modeBits &= ~02000; /* turn off sgid for file. */
1583 #endif
1584         }
1585     }
1586     if (Caller & TVS_SSTATUS) { /* update time on non-status change */
1587         /* store status, must explicitly request to change the date */
1588         if (InStatus->Mask & AFS_SETMODTIME)
1589             targetptr->disk.unixModifyTime = InStatus->ClientModTime;
1590     } else {                    /* other: date always changes, but perhaps to what is specified by caller */
1591         targetptr->disk.unixModifyTime =
1592             (InStatus->Mask & AFS_SETMODTIME ? InStatus->
1593              ClientModTime : FT_ApproxTime());
1594     }
1595     if (InStatus->Mask & AFS_SETOWNER) {
1596         /* admin is allowed to do chmod, chown as well as chown, chmod. */
1597         if (VanillaUser(client)) {
1598             targetptr->disk.modeBits &= ~04000; /* turn off suid for file. */
1599 #ifdef CREATE_SGUID_ADMIN_ONLY
1600             targetptr->disk.modeBits &= ~02000; /* turn off sgid for file. */
1601 #endif
1602         }
1603         targetptr->disk.owner = InStatus->Owner;
1604         if (VolumeRootVnode(targetptr)) {
1605             Error errorCode = 0;        /* what should be done with this? */
1606
1607             V_owner(targetptr->volumePtr) = InStatus->Owner;
1608             VUpdateVolume(&errorCode, targetptr->volumePtr);
1609         }
1610     }
1611     if (InStatus->Mask & AFS_SETMODE) {
1612         int modebits = InStatus->UnixModeBits;
1613 #define CREATE_SGUID_ADMIN_ONLY 1
1614 #ifdef CREATE_SGUID_ADMIN_ONLY
1615         if (VanillaUser(client))
1616             modebits = modebits & 0777;
1617 #endif
1618         if (VanillaUser(client)) {
1619             targetptr->disk.modeBits = modebits;
1620         } else {
1621             targetptr->disk.modeBits = modebits;
1622             switch (Caller) {
1623             case TVS_SDATA:
1624                 osi_audit(PrivSetID, 0, AUD_ID, client->ViceId, AUD_INT,
1625                           CHK_STOREDATA, AUD_END);
1626                 break;
1627             case TVS_CFILE:
1628             case TVS_SSTATUS:
1629                 osi_audit(PrivSetID, 0, AUD_ID, client->ViceId, AUD_INT,
1630                           CHK_STORESTATUS, AUD_END);
1631                 break;
1632             default:
1633                 break;
1634             }
1635         }
1636     }
1637     targetptr->disk.serverModifyTime = FT_ApproxTime();
1638     if (InStatus->Mask & AFS_SETGROUP)
1639         targetptr->disk.group = InStatus->Group;
1640     /* vnode changed : to be written back by VPutVnode */
1641     targetptr->changed_newTime = 1;
1642
1643 }                               /*Update_TargetVnodeStatus */
1644
1645
1646 /*
1647  * Fills the CallBack structure with the expiration time and type of callback
1648  * structure. Warning: this function is currently incomplete.
1649  */
1650 static void
1651 SetCallBackStruct(afs_uint32 CallBackTime, struct AFSCallBack *CallBack)
1652 {
1653     /* CallBackTime could not be 0 */
1654     if (CallBackTime == 0) {
1655         ViceLog(0, ("WARNING: CallBackTime == 0!\n"));
1656         CallBack->ExpirationTime = 0;
1657     } else
1658         CallBack->ExpirationTime = CallBackTime - FT_ApproxTime();
1659     CallBack->CallBackVersion = CALLBACK_VERSION;
1660     CallBack->CallBackType = CB_SHARED; /* The default for now */
1661
1662 }                               /*SetCallBackStruct */
1663
1664
1665 /*
1666  * Adjusts (Subtract) "length" number of blocks from the volume's disk
1667  * allocation; if some error occured (exceeded volume quota or partition
1668  * was full, or whatever), it frees the space back and returns the code.
1669  * We usually pre-adjust the volume space to make sure that there's
1670  * enough space before consuming some.
1671  */
1672 static afs_int32
1673 AdjustDiskUsage(Volume * volptr, afs_sfsize_t length,
1674                 afs_sfsize_t checkLength)
1675 {
1676     Error rc;
1677     Error nc;
1678
1679     VAdjustDiskUsage(&rc, volptr, length, checkLength);
1680     if (rc) {
1681         VAdjustDiskUsage(&nc, volptr, -length, 0);
1682         if (rc == VOVERQUOTA) {
1683             ViceLog(2,
1684                     ("Volume %u (%s) is full\n", V_id(volptr),
1685                      V_name(volptr)));
1686             return (rc);
1687         }
1688         if (rc == VDISKFULL) {
1689             ViceLog(0,
1690                     ("Partition %s that contains volume %u is full\n",
1691                      volptr->partition->name, V_id(volptr)));
1692             return (rc);
1693         }
1694         ViceLog(0, ("Got error return %d from VAdjustDiskUsage\n", rc));
1695         return (rc);
1696     }
1697     return (0);
1698
1699 }                               /*AdjustDiskUsage */
1700
1701 /*
1702  * Common code that handles the creation of a new file (SAFS_CreateFile and
1703  * SAFS_Symlink) or a new dir (SAFS_MakeDir)
1704  */
1705 static afs_int32
1706 Alloc_NewVnode(Vnode * parentptr, DirHandle * dir, Volume * volptr,
1707                Vnode ** targetptr, char *Name, struct AFSFid *OutFid,
1708                int FileType, afs_sfsize_t BlocksPreallocatedForVnode)
1709 {
1710     Error errorCode = 0;                /* Error code returned back */
1711     Error temp;
1712     Inode inode = 0;
1713     Inode nearInode;            /* hint for inode allocation in solaris */
1714
1715     if ((errorCode =
1716          AdjustDiskUsage(volptr, BlocksPreallocatedForVnode,
1717                          BlocksPreallocatedForVnode))) {
1718         ViceLog(25,
1719                 ("Insufficient space to allocate %" AFS_INT64_FMT " blocks\n",
1720                  (afs_intmax_t) BlocksPreallocatedForVnode));
1721         return (errorCode);
1722     }
1723
1724     *targetptr = VAllocVnode(&errorCode, volptr, FileType);
1725     if (errorCode != 0) {
1726         VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1727         return (errorCode);
1728     }
1729     OutFid->Volume = V_id(volptr);
1730     OutFid->Vnode = (*targetptr)->vnodeNumber;
1731     OutFid->Unique = (*targetptr)->disk.uniquifier;
1732
1733     nearInode = VN_GET_INO(parentptr);  /* parent is also in same vol */
1734
1735     /* create the inode now itself */
1736     inode =
1737         IH_CREATE(V_linkHandle(volptr), V_device(volptr),
1738                   VPartitionPath(V_partition(volptr)), nearInode,
1739                   V_id(volptr), (*targetptr)->vnodeNumber,
1740                   (*targetptr)->disk.uniquifier, 1);
1741
1742     /* error in creating inode */
1743     if (!VALID_INO(inode)) {
1744         ViceLog(0,
1745                 ("Volume : %u vnode = %u Failed to create inode: errno = %d\n",
1746                  (*targetptr)->volumePtr->header->diskstuff.id,
1747                  (*targetptr)->vnodeNumber, errno));
1748         VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1749         (*targetptr)->delete = 1;       /* delete vnode */
1750         return ENOSPC;
1751     }
1752     VN_SET_INO(*targetptr, inode);
1753     IH_INIT(((*targetptr)->handle), V_device(volptr), V_id(volptr), inode);
1754
1755     /* copy group from parent dir */
1756     (*targetptr)->disk.group = parentptr->disk.group;
1757
1758     if (parentptr->disk.cloned) {
1759         ViceLog(25, ("Alloc_NewVnode : CopyOnWrite called\n"));
1760         if ((errorCode = CopyOnWrite(parentptr, volptr, 0, MAXFSIZE))) {        /* disk full */
1761             ViceLog(25, ("Alloc_NewVnode : CopyOnWrite failed\n"));
1762             /* delete the vnode previously allocated */
1763             (*targetptr)->delete = 1;
1764             VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1765             IH_REALLYCLOSE((*targetptr)->handle);
1766             if (IH_DEC(V_linkHandle(volptr), inode, V_parentId(volptr)))
1767                 ViceLog(0,
1768                         ("Alloc_NewVnode: partition %s idec %s failed\n",
1769                          volptr->partition->name, PrintInode(NULL, inode)));
1770             IH_RELEASE((*targetptr)->handle);
1771
1772             return errorCode;
1773         }
1774     }
1775
1776     /* add the name to the directory */
1777     SetDirHandle(dir, parentptr);
1778     if ((errorCode = Create(dir, (char *)Name, OutFid))) {
1779         (*targetptr)->delete = 1;
1780         VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1781         IH_REALLYCLOSE((*targetptr)->handle);
1782         if (IH_DEC(V_linkHandle(volptr), inode, V_parentId(volptr)))
1783             ViceLog(0,
1784                     ("Alloc_NewVnode: partition %s idec %s failed\n",
1785                      volptr->partition->name, PrintInode(NULL, inode)));
1786         IH_RELEASE((*targetptr)->handle);
1787         return (errorCode);
1788     }
1789     DFlush();
1790     return (0);
1791
1792 }                               /*Alloc_NewVnode */
1793
1794
1795 /*
1796  * Handle all the lock-related code (SAFS_SetLock, SAFS_ExtendLock and
1797  * SAFS_ReleaseLock)
1798  */
1799 static afs_int32
1800 HandleLocking(Vnode * targetptr, struct client *client, afs_int32 rights, ViceLockType LockingType)
1801 {
1802     int Time;                   /* Used for time */
1803     int writeVnode = targetptr->changed_oldTime;        /* save original status */
1804
1805     targetptr->changed_oldTime = 1;     /* locking doesn't affect any time stamp */
1806     Time = FT_ApproxTime();
1807     switch (LockingType) {
1808     case LockRead:
1809     case LockWrite:
1810         if (Time > targetptr->disk.lock.lockTime)
1811             targetptr->disk.lock.lockTime = targetptr->disk.lock.lockCount =
1812                 0;
1813         Time += AFS_LOCKWAIT;
1814         if (LockingType == LockRead) {
1815             if ( !(rights & PRSFS_LOCK) && 
1816                  !(rights & PRSFS_WRITE) &&
1817                  !(OWNSp(client, targetptr) && (rights & PRSFS_INSERT)) )
1818                     return(EACCES);
1819
1820             if (targetptr->disk.lock.lockCount >= 0) {
1821                 ++(targetptr->disk.lock.lockCount);
1822                 targetptr->disk.lock.lockTime = Time;
1823             } else
1824                 return (EAGAIN);
1825         } else if (LockingType == LockWrite) {
1826             if ( !(rights & PRSFS_WRITE) && 
1827                  !(OWNSp(client, targetptr) && (rights & PRSFS_INSERT)) )
1828                 return(EACCES);
1829
1830             if (targetptr->disk.lock.lockCount == 0) {
1831                 targetptr->disk.lock.lockCount = -1;
1832                 targetptr->disk.lock.lockTime = Time;
1833             } else
1834                 return (EAGAIN);
1835         }
1836         break;
1837     case LockExtend:
1838         Time += AFS_LOCKWAIT;
1839         if (targetptr->disk.lock.lockCount != 0)
1840             targetptr->disk.lock.lockTime = Time;
1841         else
1842             return (EINVAL);
1843         break;
1844     case LockRelease:
1845         if ((--targetptr->disk.lock.lockCount) <= 0)
1846             targetptr->disk.lock.lockCount = targetptr->disk.lock.lockTime =
1847                 0;
1848         break;
1849     default:
1850         targetptr->changed_oldTime = writeVnode;        /* restore old status */
1851         ViceLog(0, ("Illegal Locking type %d\n", LockingType));
1852     }
1853     return (0);
1854 }                               /*HandleLocking */
1855
1856 /* Checks if caller has the proper AFS and Unix (WRITE) access permission to the target directory; Prfs_Mode refers to the AFS Mode operation while rights contains the caller's access permissions to the directory. */
1857
1858 static afs_int32
1859 CheckWriteMode(Vnode * targetptr, afs_int32 rights, int Prfs_Mode)
1860 {
1861     if (readonlyServer)
1862         return (VREADONLY);
1863     if (!(rights & Prfs_Mode))
1864         return (EACCES);
1865     if ((targetptr->disk.type != vDirectory)
1866         && (!(targetptr->disk.modeBits & OWNERWRITE)))
1867         return (EACCES);
1868     return (0);
1869 }
1870
1871 /*
1872  * If some flags (i.e. min or max quota) are set, the volume's in disk
1873  * label is updated; Name, OfflineMsg, and Motd are also reflected in the
1874  * update, if applicable.
1875  */
1876 static afs_int32
1877 RXUpdate_VolumeStatus(Volume * volptr, AFSStoreVolumeStatus * StoreVolStatus,
1878                       char *Name, char *OfflineMsg, char *Motd)
1879 {
1880     Error errorCode = 0;
1881
1882     if (StoreVolStatus->Mask & AFS_SETMINQUOTA)
1883         V_minquota(volptr) = StoreVolStatus->MinQuota;
1884     if (StoreVolStatus->Mask & AFS_SETMAXQUOTA)
1885         V_maxquota(volptr) = StoreVolStatus->MaxQuota;
1886     if (strlen(OfflineMsg) > 0) {
1887         strcpy(V_offlineMessage(volptr), OfflineMsg);
1888     }
1889     if (strlen(Name) > 0) {
1890         strcpy(V_name(volptr), Name);
1891     }
1892 #if OPENAFS_VOL_STATS
1893     /*
1894      * We don't overwrite the motd field, since it's now being used
1895      * for stats
1896      */
1897 #else
1898     if (strlen(Motd) > 0) {
1899         strcpy(V_motd(volptr), Motd);
1900     }
1901 #endif /* FS_STATS_DETAILED */
1902     VUpdateVolume(&errorCode, volptr);
1903     return (errorCode);
1904
1905 }                               /*RXUpdate_VolumeStatus */
1906
1907
1908 static afs_int32
1909 RXGetVolumeStatus(AFSFetchVolumeStatus * status, char **name, char **offMsg,
1910                   char **motd, Volume * volptr)
1911 {
1912     int temp;
1913
1914     status->Vid = V_id(volptr);
1915     status->ParentId = V_parentId(volptr);
1916     status->Online = V_inUse(volptr);
1917     status->InService = V_inService(volptr);
1918     status->Blessed = V_blessed(volptr);
1919     status->NeedsSalvage = V_needsSalvaged(volptr);
1920     if (VolumeWriteable(volptr))
1921         status->Type = ReadWrite;
1922     else
1923         status->Type = ReadOnly;
1924     status->MinQuota = V_minquota(volptr);
1925     status->MaxQuota = V_maxquota(volptr);
1926     status->BlocksInUse = V_diskused(volptr);
1927     status->PartBlocksAvail = RoundInt64ToInt32(volptr->partition->free);
1928     status->PartMaxBlocks = RoundInt64ToInt32(volptr->partition->totalUsable);
1929
1930     /* now allocate and copy these things; they're freed by the RXGEN stub */
1931     temp = strlen(V_name(volptr)) + 1;
1932     *name = malloc(temp);
1933     if (!*name) {
1934         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1935         assert(0);
1936     }
1937     strcpy(*name, V_name(volptr));
1938     temp = strlen(V_offlineMessage(volptr)) + 1;
1939     *offMsg = malloc(temp);
1940     if (!*offMsg) {
1941         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1942         assert(0);
1943     }
1944     strcpy(*offMsg, V_offlineMessage(volptr));
1945 #if OPENAFS_VOL_STATS
1946     *motd = malloc(1);
1947     if (!*motd) {
1948         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1949         assert(0);
1950     }
1951     strcpy(*motd, nullString);
1952 #else
1953     temp = strlen(V_motd(volptr)) + 1;
1954     *motd = malloc(temp);
1955     if (!*motd) {
1956         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1957         assert(0);
1958     }
1959     strcpy(*motd, V_motd(volptr));
1960 #endif /* FS_STATS_DETAILED */
1961     return 0;
1962 }                               /*RXGetVolumeStatus */
1963
1964
1965 static afs_int32
1966 FileNameOK(register char *aname)
1967 {
1968     register afs_int32 i, tc;
1969     i = strlen(aname);
1970     if (i >= 4) {
1971         /* watch for @sys on the right */
1972         if (strcmp(aname + i - 4, "@sys") == 0)
1973             return 0;
1974     }
1975     while ((tc = *aname++)) {
1976         if (tc == '/')
1977             return 0;           /* very bad character to encounter */
1978     }
1979     return 1;                   /* file name is ok */
1980
1981 }                               /*FileNameOK */
1982
1983
1984 /*
1985  * This variant of symlink is expressly to support the AFS/DFS translator
1986  * and is not supported by the AFS fileserver. We just return EINVAL.
1987  * The cache manager should not generate this call to an AFS cache manager.
1988  */
1989 afs_int32
1990 SRXAFS_DFSSymlink(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
1991                   char *LinkContents, struct AFSStoreStatus *InStatus,
1992                   struct AFSFid *OutFid, struct AFSFetchStatus *OutFidStatus,
1993                   struct AFSFetchStatus *OutDirStatus,
1994                   struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
1995 {
1996     return EINVAL;
1997 }
1998
1999 afs_int32
2000 SRXAFS_FsCmd(struct rx_call * acall, struct AFSFid * Fid,
2001                     struct FsCmdInputs * Inputs,
2002                     struct FsCmdOutputs * Outputs)
2003 {
2004     afs_int32 code = 0;
2005
2006     switch (Inputs->command) {
2007     default:
2008         code = EINVAL;
2009     }
2010     ViceLog(1,("FsCmd: cmd = %d, code=%d\n", 
2011                         Inputs->command, Outputs->code));
2012     return code;
2013 }
2014
2015 #ifdef AFS_NT40_ENV
2016 static struct afs_buffer {
2017     struct afs_buffer *next;
2018 } *freeBufferList = 0;
2019 static int afs_buffersAlloced = 0;
2020
2021 static
2022 FreeSendBuffer(register struct afs_buffer *adata)
2023 {
2024     FS_LOCK;
2025     afs_buffersAlloced--;
2026     adata->next = freeBufferList;
2027     freeBufferList = adata;
2028     FS_UNLOCK;
2029     return 0;
2030
2031 }                               /*FreeSendBuffer */
2032
2033 /* allocate space for sender */
2034 static char *
2035 AllocSendBuffer()
2036 {
2037     register struct afs_buffer *tp;
2038
2039     FS_LOCK;
2040     afs_buffersAlloced++;
2041     if (!freeBufferList) {
2042         char *tmp;
2043         FS_UNLOCK;
2044         tmp = malloc(sendBufSize);
2045         if (!tmp) {
2046             ViceLog(0, ("Failed malloc in AllocSendBuffer\n"));
2047             assert(0);
2048         }
2049         return tmp;
2050     }
2051     tp = freeBufferList;
2052     freeBufferList = tp->next;
2053     FS_UNLOCK;
2054     return (char *)tp;
2055
2056 }                               /*AllocSendBuffer */
2057 #endif /* AFS_NT40_ENV */
2058
2059 /*
2060  * This routine returns the status info associated with the targetptr vnode
2061  * in the AFSFetchStatus structure.  Some of the newer fields, such as
2062  * SegSize and Group are not yet implemented
2063  */
2064 static
2065     void
2066 GetStatus(Vnode * targetptr, AFSFetchStatus * status, afs_int32 rights,
2067           afs_int32 anyrights, Vnode * parentptr)
2068 {
2069     /* initialize return status from a vnode  */
2070     status->InterfaceVersion = 1;
2071     status->SyncCounter = status->dataVersionHigh = status->lockCount =
2072         status->errorCode = 0;
2073     status->ResidencyMask = 1;  /* means for MR-AFS: file in /vicepr-partition */
2074     if (targetptr->disk.type == vFile)
2075         status->FileType = File;
2076     else if (targetptr->disk.type == vDirectory)
2077         status->FileType = Directory;
2078     else if (targetptr->disk.type == vSymlink)
2079         status->FileType = SymbolicLink;
2080     else
2081         status->FileType = Invalid;     /*invalid type field */
2082     status->LinkCount = targetptr->disk.linkCount;
2083     {
2084         afs_fsize_t targetLen;
2085         VN_GET_LEN(targetLen, targetptr);
2086         SplitOffsetOrSize(targetLen, status->Length_hi, status->Length);
2087     }
2088     status->DataVersion = targetptr->disk.dataVersion;
2089     status->Author = targetptr->disk.author;
2090     status->Owner = targetptr->disk.owner;
2091     status->CallerAccess = rights;
2092     status->AnonymousAccess = anyrights;
2093     status->UnixModeBits = targetptr->disk.modeBits;
2094     status->ClientModTime = targetptr->disk.unixModifyTime;     /* This might need rework */
2095     status->ParentVnode =
2096         (status->FileType ==
2097          Directory ? targetptr->vnodeNumber : parentptr->vnodeNumber);
2098     status->ParentUnique =
2099         (status->FileType ==
2100          Directory ? targetptr->disk.uniquifier : parentptr->disk.uniquifier);
2101     status->ServerModTime = targetptr->disk.serverModifyTime;
2102     status->Group = targetptr->disk.group;
2103     status->lockCount = targetptr->disk.lock.lockCount;
2104     status->errorCode = 0;
2105
2106 }                               /*GetStatus */
2107
2108 static
2109   afs_int32
2110 common_FetchData64(struct rx_call *acall, struct AFSFid *Fid,
2111                    afs_sfsize_t Pos, afs_sfsize_t Len,
2112                    struct AFSFetchStatus *OutStatus,
2113                    struct AFSCallBack *CallBack, struct AFSVolSync *Sync,
2114                    int type)
2115 {
2116     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2117     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if vptr is a file */
2118     Vnode tparentwhentargetnotdir;      /* parent vnode for GetStatus */
2119     Error errorCode = 0;                /* return code to caller */
2120     Error fileCode = 0;         /* return code from vol package */
2121     Volume *volptr = 0;         /* pointer to the volume */
2122     struct client *client = 0;  /* pointer to the client data */
2123     struct rx_connection *tcon; /* the connection we're part of */
2124     struct host *thost;
2125     afs_int32 rights, anyrights;        /* rights for this and any user */
2126     struct client *t_client = NULL;     /* tmp ptr to client data */
2127     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2128 #if FS_STATS_DETAILED
2129     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2130     struct fs_stats_xferData *xferP;    /* Ptr to this op's byte size struct */
2131     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2132     struct timeval xferStartTime, xferStopTime; /* Start/stop times for xfer portion */
2133     struct timeval elapsedTime; /* Transfer time */
2134     afs_sfsize_t bytesToXfer;   /* # bytes to xfer */
2135     afs_sfsize_t bytesXferred;  /* # bytes actually xferred */
2136     int readIdx;                /* Index of read stats array to bump */
2137     static afs_int32 tot_bytesXferred;  /* shared access protected by FS_LOCK */
2138
2139     /*
2140      * Set our stats pointers, remember when the RPC operation started, and
2141      * tally the operation.
2142      */
2143     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHDATA]);
2144     xferP = &(afs_FullPerfStats.det.xferOpTimes[FS_STATS_XFERIDX_FETCHDATA]);
2145     FS_LOCK;
2146     (opP->numOps)++;
2147     FS_UNLOCK;
2148     FT_GetTimeOfDay(&opStartTime, 0);
2149 #endif /* FS_STATS_DETAILED */
2150
2151     ViceLog(1,
2152             ("SRXAFS_FetchData, Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2153              Fid->Unique));
2154     FS_LOCK;
2155     AFSCallStats.FetchData++, AFSCallStats.TotalCalls++;
2156     FS_UNLOCK;
2157     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2158         goto Bad_FetchData;
2159
2160     /* Get ptr to client data for user Id for logging */
2161     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2162     logHostAddr.s_addr = rxr_HostOf(tcon);
2163     ViceLog(5,
2164             ("SRXAFS_FetchData, Fid = %u.%u.%u, Host %s:%d, Id %d\n",
2165              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2166              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2167     /*
2168      * Get volume/vnode for the fetched file; caller's access rights to
2169      * it are also returned
2170      */
2171     if ((errorCode =
2172          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
2173                           &parentwhentargetnotdir, &client, READ_LOCK,
2174                           &rights, &anyrights)))
2175         goto Bad_FetchData;
2176
2177     SetVolumeSync(Sync, volptr);
2178
2179 #if FS_STATS_DETAILED
2180     /*
2181      * Remember that another read operation was performed.
2182      */
2183     FS_LOCK;
2184     if (client->InSameNetwork)
2185         readIdx = VOL_STATS_SAME_NET;
2186     else
2187         readIdx = VOL_STATS_DIFF_NET;
2188     V_stat_reads(volptr, readIdx)++;
2189     if (client->ViceId != AnonymousID) {
2190         V_stat_reads(volptr, readIdx + 1)++;
2191     }
2192     FS_UNLOCK;
2193 #endif /* FS_STATS_DETAILED */
2194     /* Check whether the caller has permission access to fetch the data */
2195     if ((errorCode =
2196          Check_PermissionRights(targetptr, client, rights, CHK_FETCHDATA, 0)))
2197         goto Bad_FetchData;
2198
2199     /*
2200      * Drop the read lock on the parent directory after saving the parent
2201      * vnode information we need to pass to GetStatus
2202      */
2203     if (parentwhentargetnotdir != NULL) {
2204         tparentwhentargetnotdir = *parentwhentargetnotdir;
2205         VPutVnode(&fileCode, parentwhentargetnotdir);
2206         assert(!fileCode || (fileCode == VSALVAGE));
2207         parentwhentargetnotdir = NULL;
2208     }
2209 #if FS_STATS_DETAILED
2210     /*
2211      * Remember when the data transfer started.
2212      */
2213     FT_GetTimeOfDay(&xferStartTime, 0);
2214 #endif /* FS_STATS_DETAILED */
2215
2216     /* actually do the data transfer */
2217 #if FS_STATS_DETAILED
2218     errorCode =
2219         FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type,
2220                           &bytesToXfer, &bytesXferred);
2221 #else
2222     if ((errorCode =
2223          FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type)))
2224         goto Bad_FetchData;
2225 #endif /* FS_STATS_DETAILED */
2226
2227 #if FS_STATS_DETAILED
2228     /*
2229      * At this point, the data transfer is done, for good or ill.  Remember
2230      * when the transfer ended, bump the number of successes/failures, and
2231      * integrate the transfer size and elapsed time into the stats.  If the
2232      * operation failed, we jump to the appropriate point.
2233      */
2234     FT_GetTimeOfDay(&xferStopTime, 0);
2235     FS_LOCK;
2236     (xferP->numXfers)++;
2237     if (!errorCode) {
2238         (xferP->numSuccesses)++;
2239
2240         /*
2241          * Bump the xfer sum by the number of bytes actually sent, NOT the
2242          * target number.
2243          */
2244         tot_bytesXferred += bytesXferred;
2245         (xferP->sumBytes) += (tot_bytesXferred >> 10);
2246         tot_bytesXferred &= 0x3FF;
2247         if (bytesXferred < xferP->minBytes)
2248             xferP->minBytes = bytesXferred;
2249         if (bytesXferred > xferP->maxBytes)
2250             xferP->maxBytes = bytesXferred;
2251
2252         /*
2253          * Tally the size of the object.  Note: we tally the actual size,
2254          * NOT the number of bytes that made it out over the wire.
2255          */
2256         if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET0)
2257             (xferP->count[0])++;
2258         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET1)
2259             (xferP->count[1])++;
2260         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET2)
2261             (xferP->count[2])++;
2262         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET3)
2263             (xferP->count[3])++;
2264         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET4)
2265             (xferP->count[4])++;
2266         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET5)
2267             (xferP->count[5])++;
2268         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET6)
2269             (xferP->count[6])++;
2270         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET7)
2271             (xferP->count[7])++;
2272         else
2273             (xferP->count[8])++;
2274
2275         fs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
2276         fs_stats_AddTo((xferP->sumTime), elapsedTime);
2277         fs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
2278         if (fs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
2279             fs_stats_TimeAssign((xferP->minTime), elapsedTime);
2280         }
2281         if (fs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
2282             fs_stats_TimeAssign((xferP->maxTime), elapsedTime);
2283         }
2284     }
2285     FS_UNLOCK;
2286     /*
2287      * Finally, go off to tell our caller the bad news in case the
2288      * fetch failed.
2289      */
2290     if (errorCode)
2291         goto Bad_FetchData;
2292 #endif /* FS_STATS_DETAILED */
2293
2294     /* write back  the OutStatus from the target vnode  */
2295     GetStatus(targetptr, OutStatus, rights, anyrights,
2296               &tparentwhentargetnotdir);
2297
2298     /* if a r/w volume, promise a callback to the caller */
2299     if (VolumeWriteable(volptr))
2300         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2301     else {
2302         struct AFSFid myFid;
2303         memset(&myFid, 0, sizeof(struct AFSFid));
2304         myFid.Volume = Fid->Volume;
2305         SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2306     }
2307
2308   Bad_FetchData:
2309     /* Update and store volume/vnode and parent vnodes back */
2310     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2311                            volptr, &client);
2312     ViceLog(2, ("SRXAFS_FetchData returns %d\n", errorCode));
2313     errorCode = CallPostamble(tcon, errorCode, thost);
2314
2315 #if FS_STATS_DETAILED
2316     FT_GetTimeOfDay(&opStopTime, 0);
2317     if (errorCode == 0) {
2318         FS_LOCK;
2319         (opP->numSuccesses)++;
2320         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2321         fs_stats_AddTo((opP->sumTime), elapsedTime);
2322         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2323         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2324             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2325         }
2326         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2327             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2328         }
2329         FS_UNLOCK;
2330     }
2331 #endif /* FS_STATS_DETAILED */
2332
2333     osi_auditU(acall, FetchDataEvent, errorCode, 
2334                AUD_ID, t_client ? t_client->ViceId : 0,
2335                AUD_FID, Fid, AUD_END);
2336     return (errorCode);
2337
2338 }                               /*SRXAFS_FetchData */
2339
2340 afs_int32
2341 SRXAFS_FetchData(struct rx_call * acall, struct AFSFid * Fid, afs_int32 Pos,
2342                  afs_int32 Len, struct AFSFetchStatus * OutStatus,
2343                  struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2344 {
2345     return common_FetchData64(acall, Fid, Pos, Len, OutStatus, CallBack, 
2346                               Sync, 0);
2347 }
2348
2349 afs_int32
2350 SRXAFS_FetchData64(struct rx_call * acall, struct AFSFid * Fid, afs_int64 Pos,
2351                    afs_int64 Len, struct AFSFetchStatus * OutStatus,
2352                    struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2353 {
2354     int code;
2355     afs_sfsize_t tPos, tLen;
2356
2357 #ifdef AFS_64BIT_ENV
2358     tPos = (afs_sfsize_t) Pos;
2359     tLen = (afs_sfsize_t) Len;
2360 #else /* AFS_64BIT_ENV */
2361     if (Pos.high || Len.high)
2362         return EFBIG;
2363     tPos = Pos.low;
2364     tLen = Len.low;
2365 #endif /* AFS_64BIT_ENV */
2366
2367     code =
2368         common_FetchData64(acall, Fid, tPos, tLen, OutStatus, CallBack, Sync,
2369                            1);
2370     return code;
2371 }
2372
2373 afs_int32
2374 SRXAFS_FetchACL(struct rx_call * acall, struct AFSFid * Fid,
2375                 struct AFSOpaque * AccessList,
2376                 struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
2377 {
2378     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2379     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2380     Error errorCode = 0;                /* return error code to caller */
2381     Volume *volptr = 0;         /* pointer to the volume */
2382     struct client *client = 0;  /* pointer to the client data */
2383     afs_int32 rights, anyrights;        /* rights for this and any user */
2384     struct rx_connection *tcon = rx_ConnectionOf(acall);
2385     struct host *thost;
2386     struct client *t_client = NULL;     /* tmp ptr to client data */
2387     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2388 #if FS_STATS_DETAILED
2389     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2390     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2391     struct timeval elapsedTime; /* Transfer time */
2392
2393     /*
2394      * Set our stats pointer, remember when the RPC operation started, and
2395      * tally the operation.
2396      */
2397     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHACL]);
2398     FS_LOCK;
2399     (opP->numOps)++;
2400     FS_UNLOCK;
2401     FT_GetTimeOfDay(&opStartTime, 0);
2402 #endif /* FS_STATS_DETAILED */
2403
2404     ViceLog(1,
2405             ("SAFS_FetchACL, Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2406              Fid->Unique));
2407     FS_LOCK;
2408     AFSCallStats.FetchACL++, AFSCallStats.TotalCalls++;
2409     FS_UNLOCK;
2410     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2411         goto Bad_FetchACL;
2412
2413     /* Get ptr to client data for user Id for logging */
2414     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2415     logHostAddr.s_addr = rxr_HostOf(tcon);
2416     ViceLog(5,
2417             ("SAFS_FetchACL, Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
2418              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2419              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2420
2421     AccessList->AFSOpaque_len = 0;
2422     AccessList->AFSOpaque_val = malloc(AFSOPAQUEMAX);
2423     if (!AccessList->AFSOpaque_val) {
2424         ViceLog(0, ("Failed malloc in SRXAFS_FetchACL\n"));
2425         assert(0);
2426     }
2427
2428     /*
2429      * Get volume/vnode for the fetched file; caller's access rights to it
2430      * are also returned
2431      */
2432     if ((errorCode =
2433          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
2434                           &parentwhentargetnotdir, &client, READ_LOCK,
2435                           &rights, &anyrights)))
2436         goto Bad_FetchACL;
2437
2438     SetVolumeSync(Sync, volptr);
2439
2440     /* Check whether we have permission to fetch the ACL */
2441     if ((errorCode =
2442          Check_PermissionRights(targetptr, client, rights, CHK_FETCHACL, 0)))
2443         goto Bad_FetchACL;
2444
2445     /* Get the Access List from the dir's vnode */
2446     if ((errorCode =
2447          RXFetch_AccessList(targetptr, parentwhentargetnotdir, AccessList)))
2448         goto Bad_FetchACL;
2449
2450     /* Get OutStatus back From the target Vnode  */
2451     GetStatus(targetptr, OutStatus, rights, anyrights,
2452               parentwhentargetnotdir);
2453
2454   Bad_FetchACL:
2455     /* Update and store volume/vnode and parent vnodes back */
2456     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2457                            volptr, &client);
2458     ViceLog(2,
2459             ("SAFS_FetchACL returns %d (ACL=%s)\n", errorCode,
2460              AccessList->AFSOpaque_val));
2461     errorCode = CallPostamble(tcon, errorCode, thost);
2462
2463 #if FS_STATS_DETAILED
2464     FT_GetTimeOfDay(&opStopTime, 0);
2465     if (errorCode == 0) {
2466         FS_LOCK;
2467         (opP->numSuccesses)++;
2468         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2469         fs_stats_AddTo((opP->sumTime), elapsedTime);
2470         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2471         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2472             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2473         }
2474         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2475             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2476         }
2477         FS_UNLOCK;
2478     }
2479 #endif /* FS_STATS_DETAILED */
2480
2481     osi_auditU(acall, FetchACLEvent, errorCode, 
2482                AUD_ID, t_client ? t_client->ViceId : 0,
2483                AUD_FID, Fid, 
2484                AUD_ACL, AccessList->AFSOpaque_val, AUD_END);
2485     return errorCode;
2486 }                               /*SRXAFS_FetchACL */
2487
2488
2489 /*
2490  * This routine is called exclusively by SRXAFS_FetchStatus(), and should be
2491  * merged into it when possible.
2492  */
2493 static
2494   afs_int32
2495 SAFSS_FetchStatus(struct rx_call *acall, struct AFSFid *Fid,
2496                   struct AFSFetchStatus *OutStatus,
2497                   struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
2498 {
2499     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2500     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2501     Error errorCode = 0;                /* return code to caller */
2502     Volume *volptr = 0;         /* pointer to the volume */
2503     struct client *client = 0;  /* pointer to the client data */
2504     afs_int32 rights, anyrights;        /* rights for this and any user */
2505     struct client *t_client = NULL;     /* tmp ptr to client data */
2506     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2507     struct rx_connection *tcon = rx_ConnectionOf(acall);
2508
2509     /* Get ptr to client data for user Id for logging */
2510     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2511     logHostAddr.s_addr = rxr_HostOf(tcon);
2512     ViceLog(1,
2513             ("SAFS_FetchStatus,  Fid = %u.%u.%u, Host %s:%d, Id %d\n",
2514              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2515              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2516     FS_LOCK;
2517     AFSCallStats.FetchStatus++, AFSCallStats.TotalCalls++;
2518     FS_UNLOCK;
2519     /*
2520      * Get volume/vnode for the fetched file; caller's rights to it are
2521      * also returned
2522      */
2523     if ((errorCode =
2524          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
2525                           &parentwhentargetnotdir, &client, READ_LOCK,
2526                           &rights, &anyrights)))
2527         goto Bad_FetchStatus;
2528
2529     /* set volume synchronization information */
2530     SetVolumeSync(Sync, volptr);
2531
2532     /* Are we allowed to fetch Fid's status? */
2533     if (targetptr->disk.type != vDirectory) {
2534         if ((errorCode =
2535              Check_PermissionRights(targetptr, client, rights,
2536                                     CHK_FETCHSTATUS, 0))) {
2537             if (rx_GetCallAbortCode(acall) == errorCode)
2538                 rx_SetCallAbortCode(acall, 0);
2539             goto Bad_FetchStatus;
2540         }
2541     }
2542
2543     /* set OutStatus From the Fid  */
2544     GetStatus(targetptr, OutStatus, rights, anyrights,
2545               parentwhentargetnotdir);
2546
2547     /* If a r/w volume, also set the CallBack state */
2548     if (VolumeWriteable(volptr))
2549         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2550     else {
2551         struct AFSFid myFid;
2552         memset(&myFid, 0, sizeof(struct AFSFid));
2553         myFid.Volume = Fid->Volume;
2554         SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2555     }
2556
2557   Bad_FetchStatus:
2558     /* Update and store volume/vnode and parent vnodes back */
2559     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2560                            volptr, &client);
2561     ViceLog(2, ("SAFS_FetchStatus returns %d\n", errorCode));
2562     return errorCode;
2563
2564 }                               /*SAFSS_FetchStatus */
2565
2566
2567 afs_int32
2568 SRXAFS_BulkStatus(struct rx_call * acall, struct AFSCBFids * Fids,
2569                   struct AFSBulkStats * OutStats, struct AFSCBs * CallBacks,
2570                   struct AFSVolSync * Sync)
2571 {
2572     register int i;
2573     afs_int32 nfiles;
2574     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2575     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2576     Error errorCode = 0;                /* return code to caller */
2577     Volume *volptr = 0;         /* pointer to the volume */
2578     struct client *client = 0;  /* pointer to the client data */
2579     afs_int32 rights, anyrights;        /* rights for this and any user */
2580     register struct AFSFid *tfid;       /* file id we're dealing with now */
2581     struct rx_connection *tcon = rx_ConnectionOf(acall);
2582     struct host *thost;
2583     struct client *t_client = NULL;     /* tmp pointer to the client data */
2584 #if FS_STATS_DETAILED
2585     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2586     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2587     struct timeval elapsedTime; /* Transfer time */
2588
2589     /*
2590      * Set our stats pointer, remember when the RPC operation started, and
2591      * tally the operation.
2592      */
2593     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_BULKSTATUS]);
2594     FS_LOCK;
2595     (opP->numOps)++;
2596     FS_UNLOCK;
2597     FT_GetTimeOfDay(&opStartTime, 0);
2598 #endif /* FS_STATS_DETAILED */
2599
2600     ViceLog(1, ("SAFS_BulkStatus\n"));
2601     FS_LOCK;
2602     AFSCallStats.TotalCalls++;
2603     FS_UNLOCK;
2604     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2605     if (nfiles <= 0) {          /* Sanity check */
2606         errorCode = EINVAL;
2607         goto Audit_and_Return;
2608     }
2609
2610     /* allocate space for return output parameters */
2611     OutStats->AFSBulkStats_val = (struct AFSFetchStatus *)
2612         malloc(nfiles * sizeof(struct AFSFetchStatus));
2613     if (!OutStats->AFSBulkStats_val) {
2614         ViceLog(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2615         assert(0);
2616     }
2617     OutStats->AFSBulkStats_len = nfiles;
2618     CallBacks->AFSCBs_val = (struct AFSCallBack *)
2619         malloc(nfiles * sizeof(struct AFSCallBack));
2620     if (!CallBacks->AFSCBs_val) {
2621         ViceLog(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2622         assert(0);
2623     }
2624     CallBacks->AFSCBs_len = nfiles;
2625
2626     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2627         goto Bad_BulkStatus;
2628
2629     tfid = Fids->AFSCBFids_val;
2630     for (i = 0; i < nfiles; i++, tfid++) {
2631         /*
2632          * Get volume/vnode for the fetched file; caller's rights to it
2633          * are also returned
2634          */
2635         if ((errorCode =
2636              GetVolumePackage(tcon, tfid, &volptr, &targetptr, DONTCHECK,
2637                               &parentwhentargetnotdir, &client, READ_LOCK,
2638                               &rights, &anyrights)))
2639             goto Bad_BulkStatus;
2640         /* set volume synchronization information, but only once per call */
2641         if (i == 0)
2642             SetVolumeSync(Sync, volptr);
2643
2644         /* Are we allowed to fetch Fid's status? */
2645         if (targetptr->disk.type != vDirectory) {
2646             if ((errorCode =
2647                  Check_PermissionRights(targetptr, client, rights,
2648                                         CHK_FETCHSTATUS, 0))) {
2649                 if (rx_GetCallAbortCode(acall) == errorCode)
2650                     rx_SetCallAbortCode(acall, 0);
2651                 goto Bad_BulkStatus;
2652             }
2653         }
2654
2655         /* set OutStatus From the Fid  */
2656         GetStatus(targetptr, &OutStats->AFSBulkStats_val[i], rights,
2657                   anyrights, parentwhentargetnotdir);
2658
2659         /* If a r/w volume, also set the CallBack state */
2660         if (VolumeWriteable(volptr))
2661             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2662                               &CallBacks->AFSCBs_val[i]);
2663         else {
2664             struct AFSFid myFid;
2665             memset(&myFid, 0, sizeof(struct AFSFid));
2666             myFid.Volume = tfid->Volume;
2667             SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2668                               &CallBacks->AFSCBs_val[i]);
2669         }
2670
2671         /* put back the file ID and volume */
2672         (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2673                                volptr, &client);
2674         parentwhentargetnotdir = (Vnode *) 0;
2675         targetptr = (Vnode *) 0;
2676         volptr = (Volume *) 0;
2677         client = (struct client *)0;
2678     }
2679
2680   Bad_BulkStatus:
2681     /* Update and store volume/vnode and parent vnodes back */
2682     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2683                            volptr, &client);
2684     errorCode = CallPostamble(tcon, errorCode, thost);
2685
2686     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2687
2688 #if FS_STATS_DETAILED
2689     FT_GetTimeOfDay(&opStopTime, 0);
2690     if (errorCode == 0) {
2691         FS_LOCK;
2692         (opP->numSuccesses)++;
2693         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2694         fs_stats_AddTo((opP->sumTime), elapsedTime);
2695         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2696         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2697             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2698         }
2699         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2700             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2701         }
2702         FS_UNLOCK;
2703     }
2704 #endif /* FS_STATS_DETAILED */
2705
2706   Audit_and_Return:
2707     ViceLog(2, ("SAFS_BulkStatus        returns %d\n", errorCode));
2708     osi_auditU(acall, BulkFetchStatusEvent, errorCode, 
2709                AUD_ID, t_client ? t_client->ViceId : 0,
2710                AUD_FIDS, Fids, AUD_END);
2711     return errorCode;
2712
2713 }                               /*SRXAFS_BulkStatus */
2714
2715
2716 afs_int32
2717 SRXAFS_InlineBulkStatus(struct rx_call * acall, struct AFSCBFids * Fids,
2718                         struct AFSBulkStats * OutStats,
2719                         struct AFSCBs * CallBacks, struct AFSVolSync * Sync)
2720 {
2721     register int i;
2722     afs_int32 nfiles;
2723     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2724     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2725     Error errorCode = 0;                /* return code to caller */
2726     Volume *volptr = 0;         /* pointer to the volume */
2727     struct client *client = 0;  /* pointer to the client data */
2728     afs_int32 rights, anyrights;        /* rights for this and any user */
2729     register struct AFSFid *tfid;       /* file id we're dealing with now */
2730     struct rx_connection *tcon;
2731     struct host *thost;
2732     struct client *t_client = NULL;     /* tmp ptr to client data */
2733     AFSFetchStatus *tstatus;
2734 #if FS_STATS_DETAILED
2735     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2736     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2737     struct timeval elapsedTime; /* Transfer time */
2738
2739     /*
2740      * Set our stats pointer, remember when the RPC operation started, and
2741      * tally the operation.
2742      */
2743     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_BULKSTATUS]);
2744     FS_LOCK;
2745     (opP->numOps)++;
2746     FS_UNLOCK;
2747     FT_GetTimeOfDay(&opStartTime, 0);
2748 #endif /* FS_STATS_DETAILED */
2749
2750     ViceLog(1, ("SAFS_InlineBulkStatus\n"));
2751     FS_LOCK;
2752     AFSCallStats.TotalCalls++;
2753     FS_UNLOCK;
2754     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2755     if (nfiles <= 0) {          /* Sanity check */
2756         errorCode = EINVAL;
2757         goto Audit_and_Return;
2758     }
2759
2760     /* allocate space for return output parameters */
2761     OutStats->AFSBulkStats_val = (struct AFSFetchStatus *)
2762         malloc(nfiles * sizeof(struct AFSFetchStatus));
2763     if (!OutStats->AFSBulkStats_val) {
2764         ViceLog(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2765         assert(0);
2766     }
2767     OutStats->AFSBulkStats_len = nfiles;
2768     CallBacks->AFSCBs_val = (struct AFSCallBack *)
2769         malloc(nfiles * sizeof(struct AFSCallBack));
2770     if (!CallBacks->AFSCBs_val) {
2771         ViceLog(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2772         assert(0);
2773     }
2774     CallBacks->AFSCBs_len = nfiles;
2775
2776     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost))) {
2777         goto Bad_InlineBulkStatus;
2778     }
2779
2780     tfid = Fids->AFSCBFids_val;
2781     for (i = 0; i < nfiles; i++, tfid++) {
2782         /*
2783          * Get volume/vnode for the fetched file; caller's rights to it
2784          * are also returned
2785          */
2786         if ((errorCode =
2787              GetVolumePackage(tcon, tfid, &volptr, &targetptr, DONTCHECK,
2788                               &parentwhentargetnotdir, &client, READ_LOCK,
2789                               &rights, &anyrights))) {
2790             tstatus = &OutStats->AFSBulkStats_val[i];
2791             tstatus->errorCode = errorCode;
2792             PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
2793                              volptr, &client);
2794             parentwhentargetnotdir = (Vnode *) 0;
2795             targetptr = (Vnode *) 0;
2796             volptr = (Volume *) 0;
2797             client = (struct client *)0;
2798             continue;
2799         }
2800
2801         /* set volume synchronization information, but only once per call */
2802         if (i == 0)
2803             SetVolumeSync(Sync, volptr);
2804
2805         /* Are we allowed to fetch Fid's status? */
2806         if (targetptr->disk.type != vDirectory) {
2807             if ((errorCode =
2808                  Check_PermissionRights(targetptr, client, rights,
2809                                         CHK_FETCHSTATUS, 0))) {
2810                 tstatus = &OutStats->AFSBulkStats_val[i];
2811                 tstatus->errorCode = errorCode;
2812                 (void)PutVolumePackage(parentwhentargetnotdir, targetptr,
2813                                        (Vnode *) 0, volptr, &client);
2814                 parentwhentargetnotdir = (Vnode *) 0;
2815                 targetptr = (Vnode *) 0;
2816                 volptr = (Volume *) 0;
2817                 client = (struct client *)0;
2818                 continue;
2819             }
2820         }
2821
2822         /* set OutStatus From the Fid  */
2823         GetStatus(targetptr,
2824                   (struct AFSFetchStatus *)&OutStats->AFSBulkStats_val[i],
2825                   rights, anyrights, parentwhentargetnotdir);
2826
2827         /* If a r/w volume, also set the CallBack state */
2828         if (VolumeWriteable(volptr))
2829             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2830                               &CallBacks->AFSCBs_val[i]);
2831         else {
2832             struct AFSFid myFid;
2833             memset(&myFid, 0, sizeof(struct AFSFid));
2834             myFid.Volume = tfid->Volume;
2835             SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2836                               &CallBacks->AFSCBs_val[i]);
2837         }
2838
2839         /* put back the file ID and volume */
2840         (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2841                                volptr, &client);
2842         parentwhentargetnotdir = (Vnode *) 0;
2843         targetptr = (Vnode *) 0;
2844         volptr = (Volume *) 0;
2845         client = (struct client *)0;
2846     }
2847
2848   Bad_InlineBulkStatus:
2849     /* Update and store volume/vnode and parent vnodes back */
2850     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2851                            volptr, &client);
2852     errorCode = CallPostamble(tcon, errorCode, thost);
2853
2854     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2855
2856 #if FS_STATS_DETAILED
2857     FT_GetTimeOfDay(&opStopTime, 0);
2858     if (errorCode == 0) {
2859         FS_LOCK;
2860         (opP->numSuccesses)++;
2861         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2862         fs_stats_AddTo((opP->sumTime), elapsedTime);
2863         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2864         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2865             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2866         }
2867         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2868             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2869         }
2870         FS_UNLOCK;
2871     }
2872 #endif /* FS_STATS_DETAILED */
2873
2874   Audit_and_Return:
2875     ViceLog(2, ("SAFS_InlineBulkStatus  returns %d\n", errorCode));
2876     osi_auditU(acall, InlineBulkFetchStatusEvent, errorCode, 
2877                AUD_ID, t_client ? t_client->ViceId : 0,
2878                AUD_FIDS, Fids, AUD_END);
2879     return 0;
2880
2881 }                               /*SRXAFS_InlineBulkStatus */
2882
2883
2884 afs_int32
2885 SRXAFS_FetchStatus(struct rx_call * acall, struct AFSFid * Fid,
2886                    struct AFSFetchStatus * OutStatus,
2887                    struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2888 {
2889     afs_int32 code;
2890     struct rx_connection *tcon;
2891     struct host *thost;
2892     struct client *t_client = NULL;     /* tmp ptr to client data */
2893 #if FS_STATS_DETAILED
2894     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2895     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2896     struct timeval elapsedTime; /* Transfer time */
2897
2898     /*
2899      * Set our stats pointer, remember when the RPC operation started, and
2900      * tally the operation.
2901      */
2902     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHSTATUS]);
2903     FS_LOCK;
2904     (opP->numOps)++;
2905     FS_UNLOCK;
2906     FT_GetTimeOfDay(&opStartTime, 0);
2907 #endif /* FS_STATS_DETAILED */
2908
2909     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2910         goto Bad_FetchStatus;
2911
2912     code = SAFSS_FetchStatus(acall, Fid, OutStatus, CallBack, Sync);
2913
2914   Bad_FetchStatus:
2915     code = CallPostamble(tcon, code, thost);
2916
2917     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2918
2919 #if FS_STATS_DETAILED
2920     FT_GetTimeOfDay(&opStopTime, 0);
2921     if (code == 0) {
2922         FS_LOCK;
2923         (opP->numSuccesses)++;
2924         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2925         fs_stats_AddTo((opP->sumTime), elapsedTime);
2926         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2927         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2928             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2929         }
2930         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2931             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2932         }
2933         FS_UNLOCK;
2934     }
2935 #endif /* FS_STATS_DETAILED */
2936
2937     osi_auditU(acall, FetchStatusEvent, code, 
2938                AUD_ID, t_client ? t_client->ViceId : 0,
2939                AUD_FID, Fid, AUD_END);
2940     return code;
2941
2942 }                               /*SRXAFS_FetchStatus */
2943
2944 static
2945   afs_int32
2946 common_StoreData64(struct rx_call *acall, struct AFSFid *Fid,
2947                    struct AFSStoreStatus *InStatus, afs_fsize_t Pos,
2948                    afs_fsize_t Length, afs_fsize_t FileLength,
2949                    struct AFSFetchStatus *OutStatus, struct AFSVolSync *Sync)
2950 {
2951     Vnode *targetptr = 0;       /* pointer to input fid */
2952     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
2953     Vnode tparentwhentargetnotdir;      /* parent vnode for GetStatus */
2954     Error errorCode = 0;                /* return code for caller */
2955     Error fileCode = 0;         /* return code from vol package */
2956     Volume *volptr = 0;         /* pointer to the volume header */
2957     struct client *client = 0;  /* pointer to client structure */
2958     afs_int32 rights, anyrights;        /* rights for this and any user */
2959     struct client *t_client = NULL;     /* tmp ptr to client data */
2960     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2961     struct rx_connection *tcon;
2962     struct host *thost;
2963 #if FS_STATS_DETAILED
2964     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2965     struct fs_stats_xferData *xferP;    /* Ptr to this op's byte size struct */
2966     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2967     struct timeval xferStartTime, xferStopTime; /* Start/stop times for xfer portion */
2968     struct timeval elapsedTime; /* Transfer time */
2969     afs_sfsize_t bytesToXfer;   /* # bytes to xfer */
2970     afs_sfsize_t bytesXferred;  /* # bytes actually xfer */
2971     static afs_int32 tot_bytesXferred;  /* shared access protected by FS_LOCK */
2972
2973     /*
2974      * Set our stats pointers, remember when the RPC operation started, and
2975      * tally the operation.
2976      */
2977     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STOREDATA]);
2978     xferP = &(afs_FullPerfStats.det.xferOpTimes[FS_STATS_XFERIDX_STOREDATA]);
2979     FS_LOCK;
2980     (opP->numOps)++;
2981     FS_UNLOCK;
2982     ViceLog(1,
2983             ("StoreData: Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2984              Fid->Unique));
2985     FT_GetTimeOfDay(&opStartTime, 0);
2986 #endif /* FS_STATS_DETAILED */
2987
2988     FS_LOCK;
2989     AFSCallStats.StoreData++, AFSCallStats.TotalCalls++;
2990     FS_UNLOCK;
2991     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2992         goto Bad_StoreData;
2993
2994     /* Get ptr to client data for user Id for logging */
2995     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2996     logHostAddr.s_addr = rxr_HostOf(tcon);
2997     ViceLog(5,
2998             ("StoreData: Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
2999              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
3000              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3001
3002     /*
3003      * Get associated volume/vnode for the stored file; caller's rights
3004      * are also returned
3005      */
3006     if ((errorCode =
3007          GetVolumePackage(tcon, Fid, &volptr, &targetptr, MustNOTBeDIR,
3008                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3009                           &rights, &anyrights))) {
3010         goto Bad_StoreData;
3011     }
3012
3013     /* set volume synchronization information */
3014     SetVolumeSync(Sync, volptr);
3015
3016     if ((targetptr->disk.type == vSymlink)) {
3017         /* Should we return a better error code here??? */
3018         errorCode = EISDIR;
3019         goto Bad_StoreData;
3020     }
3021
3022     /* Check if we're allowed to store the data */
3023     if ((errorCode =
3024          Check_PermissionRights(targetptr, client, rights, CHK_STOREDATA,
3025                                 InStatus))) {
3026         goto Bad_StoreData;
3027     }
3028
3029     /*
3030      * Drop the read lock on the parent directory after saving the parent
3031      * vnode information we need to pass to GetStatus
3032      */
3033     if (parentwhentargetnotdir != NULL) {
3034         tparentwhentargetnotdir = *parentwhentargetnotdir;
3035         VPutVnode(&fileCode, parentwhentargetnotdir);
3036         assert(!fileCode || (fileCode == VSALVAGE));
3037         parentwhentargetnotdir = NULL;
3038     }
3039 #if FS_STATS_DETAILED
3040     /*
3041      * Remember when the data transfer started.
3042      */
3043     FT_GetTimeOfDay(&xferStartTime, 0);
3044 #endif /* FS_STATS_DETAILED */
3045
3046     /* Do the actual storing of the data */
3047 #if FS_STATS_DETAILED
3048     errorCode =
3049         StoreData_RXStyle(volptr, targetptr, Fid, client, acall, Pos, Length,
3050                           FileLength, (InStatus->Mask & AFS_FSYNC),
3051                           &bytesToXfer, &bytesXferred);
3052 #else
3053     errorCode =
3054         StoreData_RXStyle(volptr, targetptr, Fid, client, acall, Pos, Length,
3055                           FileLength, (InStatus->Mask & AFS_FSYNC));
3056     if (errorCode && (!targetptr->changed_newTime))
3057         goto Bad_StoreData;
3058 #endif /* FS_STATS_DETAILED */
3059 #if FS_STATS_DETAILED
3060     /*
3061      * At this point, the data transfer is done, for good or ill.  Remember
3062      * when the transfer ended, bump the number of successes/failures, and
3063      * integrate the transfer size and elapsed time into the stats.  If the
3064      * operation failed, we jump to the appropriate point.
3065      */
3066     FT_GetTimeOfDay(&xferStopTime, 0);
3067     FS_LOCK;
3068     (xferP->numXfers)++;
3069     if (!errorCode) {
3070         (xferP->numSuccesses)++;
3071
3072         /*
3073          * Bump the xfer sum by the number of bytes actually sent, NOT the
3074          * target number.
3075          */
3076         tot_bytesXferred += bytesXferred;
3077         (xferP->sumBytes) += (tot_bytesXferred >> 10);
3078         tot_bytesXferred &= 0x3FF;
3079         if (bytesXferred < xferP->minBytes)
3080             xferP->minBytes = bytesXferred;
3081         if (bytesXferred > xferP->maxBytes)
3082             xferP->maxBytes = bytesXferred;
3083
3084         /*
3085          * Tally the size of the object.  Note: we tally the actual size,
3086          * NOT the number of bytes that made it out over the wire.
3087          */
3088         if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET0)
3089             (xferP->count[0])++;
3090         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET1)
3091             (xferP->count[1])++;
3092         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET2)
3093             (xferP->count[2])++;
3094         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET3)
3095             (xferP->count[3])++;
3096         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET4)
3097             (xferP->count[4])++;
3098         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET5)
3099             (xferP->count[5])++;
3100         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET6)
3101             (xferP->count[6])++;
3102         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET7)
3103             (xferP->count[7])++;
3104         else
3105             (xferP->count[8])++;
3106
3107         fs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
3108         fs_stats_AddTo((xferP->sumTime), elapsedTime);
3109         fs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
3110         if (fs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
3111             fs_stats_TimeAssign((xferP->minTime), elapsedTime);
3112         }
3113         if (fs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
3114             fs_stats_TimeAssign((xferP->maxTime), elapsedTime);
3115         }
3116     }
3117     FS_UNLOCK;
3118     /*
3119      * Finally, go off to tell our caller the bad news in case the
3120      * store failed.
3121      */
3122     if (errorCode && (!targetptr->changed_newTime))
3123         goto Bad_StoreData;
3124 #endif /* FS_STATS_DETAILED */
3125
3126     /* Update the status of the target's vnode */
3127     Update_TargetVnodeStatus(targetptr, TVS_SDATA, client, InStatus,
3128                              targetptr, volptr, 0);
3129
3130     /* Get the updated File's status back to the caller */
3131     GetStatus(targetptr, OutStatus, rights, anyrights,
3132               &tparentwhentargetnotdir);
3133
3134   Bad_StoreData:
3135     /* Update and store volume/vnode and parent vnodes back */
3136     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
3137                            volptr, &client);
3138     ViceLog(2, ("SAFS_StoreData returns %d\n", errorCode));
3139
3140     errorCode = CallPostamble(tcon, errorCode, thost);
3141
3142 #if FS_STATS_DETAILED
3143     FT_GetTimeOfDay(&opStopTime, 0);
3144     if (errorCode == 0) {
3145         FS_LOCK;
3146         (opP->numSuccesses)++;
3147         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3148         fs_stats_AddTo((opP->sumTime), elapsedTime);
3149         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3150         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3151             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3152         }
3153         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3154             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3155         }
3156         FS_UNLOCK;
3157     }
3158 #endif /* FS_STATS_DETAILED */
3159     osi_auditU(acall, StoreDataEvent, errorCode, 
3160                AUD_ID, t_client ? t_client->ViceId : 0,
3161                AUD_FID, Fid, AUD_END);
3162     return (errorCode);
3163 }                               /*common_StoreData64 */
3164
3165 afs_int32
3166 SRXAFS_StoreData(struct rx_call * acall, struct AFSFid * Fid,
3167                  struct AFSStoreStatus * InStatus, afs_uint32 Pos,
3168                  afs_uint32 Length, afs_uint32 FileLength,
3169                  struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
3170 {
3171     if (FileLength > 0x7fffffff || Pos > 0x7fffffff || 
3172         (0x7fffffff - Pos) < Length)
3173         return EFBIG;
3174
3175     return common_StoreData64(acall, Fid, InStatus, Pos, Length, FileLength,
3176                               OutStatus, Sync);
3177 }                               /*SRXAFS_StoreData */
3178
3179 afs_int32
3180 SRXAFS_StoreData64(struct rx_call * acall, struct AFSFid * Fid,
3181                    struct AFSStoreStatus * InStatus, afs_uint64 Pos,
3182                    afs_uint64 Length, afs_uint64 FileLength,
3183                    struct AFSFetchStatus * OutStatus,
3184                    struct AFSVolSync * Sync)
3185 {
3186     int code;
3187     afs_fsize_t tPos;
3188     afs_fsize_t tLength;
3189     afs_fsize_t tFileLength;
3190
3191 #ifdef AFS_64BIT_ENV
3192     tPos = (afs_fsize_t) Pos;
3193     tLength = (afs_fsize_t) Length;
3194     tFileLength = (afs_fsize_t) FileLength;
3195 #else /* AFS_64BIT_ENV */
3196     if (FileLength.high)
3197         return EFBIG;
3198     tPos = Pos.low;
3199     tLength = Length.low;
3200     tFileLength = FileLength.low;
3201 #endif /* AFS_64BIT_ENV */
3202
3203     code =
3204         common_StoreData64(acall, Fid, InStatus, tPos, tLength, tFileLength,
3205                            OutStatus, Sync);
3206     return code;
3207 }
3208
3209 afs_int32
3210 SRXAFS_StoreACL(struct rx_call * acall, struct AFSFid * Fid,
3211                 struct AFSOpaque * AccessList,
3212                 struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
3213 {
3214     Vnode *targetptr = 0;       /* pointer to input fid */
3215     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
3216     Error errorCode = 0;                /* return code for caller */
3217     struct AFSStoreStatus InStatus;     /* Input status for fid */
3218     Volume *volptr = 0;         /* pointer to the volume header */
3219     struct client *client = 0;  /* pointer to client structure */
3220     afs_int32 rights, anyrights;        /* rights for this and any user */
3221     struct rx_connection *tcon;
3222     struct host *thost;
3223     struct client *t_client = NULL;     /* tmp ptr to client data */
3224     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3225 #if FS_STATS_DETAILED
3226     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3227     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3228     struct timeval elapsedTime; /* Transfer time */
3229
3230     /*
3231      * Set our stats pointer, remember when the RPC operation started, and
3232      * tally the operation.
3233      */
3234     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STOREACL]);
3235     FS_LOCK;
3236     (opP->numOps)++;
3237     FS_UNLOCK;
3238     FT_GetTimeOfDay(&opStartTime, 0);
3239 #endif /* FS_STATS_DETAILED */
3240     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3241         goto Bad_StoreACL;
3242
3243     /* Get ptr to client data for user Id for logging */
3244     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3245     logHostAddr.s_addr = rxr_HostOf(tcon);
3246     ViceLog(1,
3247             ("SAFS_StoreACL, Fid = %u.%u.%u, ACL=%s, Host %s:%d, Id %d\n",
3248              Fid->Volume, Fid->Vnode, Fid->Unique, AccessList->AFSOpaque_val,
3249              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3250     FS_LOCK;
3251     AFSCallStats.StoreACL++, AFSCallStats.TotalCalls++;
3252     FS_UNLOCK;
3253     InStatus.Mask = 0;          /* not storing any status */
3254
3255     /*
3256      * Get associated volume/vnode for the target dir; caller's rights
3257      * are also returned.
3258      */
3259     if ((errorCode =
3260          GetVolumePackage(tcon, Fid, &volptr, &targetptr, MustBeDIR,
3261                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3262                           &rights, &anyrights))) {
3263         goto Bad_StoreACL;
3264     }
3265
3266     /* set volume synchronization information */
3267     SetVolumeSync(Sync, volptr);
3268
3269     /* Check if we have permission to change the dir's ACL */
3270     if ((errorCode =
3271          Check_PermissionRights(targetptr, client, rights, CHK_STOREACL,
3272                                 &InStatus))) {
3273         goto Bad_StoreACL;
3274     }
3275
3276     /* Build and store the new Access List for the dir */
3277     if ((errorCode = RXStore_AccessList(targetptr, AccessList))) {
3278         goto Bad_StoreACL;
3279     }
3280
3281     targetptr->changed_newTime = 1;     /* status change of directory */
3282
3283     /* convert the write lock to a read lock before breaking callbacks */
3284     VVnodeWriteToRead(&errorCode, targetptr);
3285     assert(!errorCode || errorCode == VSALVAGE);
3286
3287     /* break call backs on the directory  */
3288     BreakCallBack(client->host, Fid, 0);
3289
3290     /* Get the updated dir's status back to the caller */
3291     GetStatus(targetptr, OutStatus, rights, anyrights, 0);
3292
3293   Bad_StoreACL:
3294     /* Update and store volume/vnode and parent vnodes back */
3295     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
3296                      volptr, &client);
3297     ViceLog(2, ("SAFS_StoreACL returns %d\n", errorCode));
3298     errorCode = CallPostamble(tcon, errorCode, thost);
3299
3300 #if FS_STATS_DETAILED
3301     FT_GetTimeOfDay(&opStopTime, 0);
3302     if (errorCode == 0) {
3303         FS_LOCK;
3304         (opP->numSuccesses)++;
3305         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3306         fs_stats_AddTo((opP->sumTime), elapsedTime);
3307         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3308         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3309             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3310         }
3311         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3312             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3313         }
3314         FS_UNLOCK;
3315     }
3316 #endif /* FS_STATS_DETAILED */
3317
3318     osi_auditU(acall, StoreACLEvent, errorCode, 
3319                AUD_ID, t_client ? t_client->ViceId : 0,
3320                AUD_FID, Fid, AUD_ACL, AccessList->AFSOpaque_val, AUD_END);
3321     return errorCode;
3322
3323 }                               /*SRXAFS_StoreACL */
3324
3325
3326 /*
3327  * Note: This routine is called exclusively from SRXAFS_StoreStatus(), and
3328  * should be merged when possible.
3329  */
3330 static afs_int32
3331 SAFSS_StoreStatus(struct rx_call *acall, struct AFSFid *Fid,
3332                   struct AFSStoreStatus *InStatus,
3333                   struct AFSFetchStatus *OutStatus, struct AFSVolSync *Sync)
3334 {
3335     Vnode *targetptr = 0;       /* pointer to input fid */
3336     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
3337     Error errorCode = 0;                /* return code for caller */
3338     Volume *volptr = 0;         /* pointer to the volume header */
3339     struct client *client = 0;  /* pointer to client structure */
3340     afs_int32 rights, anyrights;        /* rights for this and any user */
3341     struct client *t_client = NULL;     /* tmp ptr to client data */
3342     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3343     struct rx_connection *tcon = rx_ConnectionOf(acall);
3344
3345     /* Get ptr to client data for user Id for logging */
3346     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3347     logHostAddr.s_addr = rxr_HostOf(tcon);
3348     ViceLog(1,
3349             ("SAFS_StoreStatus,  Fid    = %u.%u.%u, Host %s:%d, Id %d\n",
3350              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
3351              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3352     FS_LOCK;
3353     AFSCallStats.StoreStatus++, AFSCallStats.TotalCalls++;
3354     FS_UNLOCK;
3355     /*
3356      * Get volume/vnode for the target file; caller's rights to it are
3357      * also returned
3358      */
3359     if ((errorCode =
3360          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
3361                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3362                           &rights, &anyrights))) {
3363         goto Bad_StoreStatus;
3364     }
3365
3366     /* set volume synchronization information */
3367     SetVolumeSync(Sync, volptr);
3368
3369     /* Check if the caller has proper permissions to store status to Fid */
3370     if ((errorCode =
3371          Check_PermissionRights(targetptr, client, rights, CHK_STORESTATUS,
3372                                 InStatus))) {
3373         goto Bad_StoreStatus;
3374     }
3375     /*
3376      * Check for a symbolic link; we can't chmod these (otherwise could
3377      * change a symlink to a mt pt or vice versa)
3378      */
3379     if (targetptr->disk.type == vSymlink && (InStatus->Mask & AFS_SETMODE)) {
3380         errorCode = EINVAL;
3381         goto Bad_StoreStatus;
3382     }
3383
3384     /* Update the status of the target's vnode */
3385     Update_TargetVnodeStatus(targetptr, TVS_SSTATUS, client, InStatus,
3386                              (parentwhentargetnotdir ? parentwhentargetnotdir
3387                               : targetptr), volptr, 0);
3388
3389     /* convert the write lock to a read lock before breaking callbacks */
3390     VVnodeWriteToRead(&errorCode, targetptr);
3391     assert(!errorCode || errorCode == VSALVAGE);
3392
3393     /* Break call backs on Fid */
3394     BreakCallBack(client->host, Fid, 0);
3395
3396     /* Return the updated status back to caller */
3397     GetStatus(targetptr, OutStatus, rights, anyrights,
3398               parentwhentargetnotdir);
3399
3400   Bad_StoreStatus:
3401     /* Update and store volume/vnode and parent vnodes back */
3402     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
3403                      volptr, &client);
3404     ViceLog(2, ("SAFS_StoreStatus returns %d\n", errorCode));
3405     return errorCode;
3406
3407 }                               /*SAFSS_StoreStatus */
3408
3409
3410 afs_int32
3411 SRXAFS_StoreStatus(struct rx_call * acall, struct AFSFid * Fid,
3412                    struct AFSStoreStatus * InStatus,
3413                    struct AFSFetchStatus * OutStatus,
3414                    struct AFSVolSync * Sync)
3415 {
3416     afs_int32 code;
3417     struct rx_connection *tcon;
3418     struct host *thost;
3419     struct client *t_client = NULL;     /* tmp ptr to client data */
3420 #if FS_STATS_DETAILED
3421     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3422     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3423     struct timeval elapsedTime; /* Transfer time */
3424
3425     /*
3426      * Set our stats pointer, remember when the RPC operation started, and
3427      * tally the operation.
3428      */
3429     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STORESTATUS]);
3430     FS_LOCK;
3431     (opP->numOps)++;
3432     FS_UNLOCK;
3433     FT_GetTimeOfDay(&opStartTime, 0);
3434 #endif /* FS_STATS_DETAILED */
3435
3436     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3437         goto Bad_StoreStatus;
3438
3439     code = SAFSS_StoreStatus(acall, Fid, InStatus, OutStatus, Sync);
3440
3441   Bad_StoreStatus:
3442     code = CallPostamble(tcon, code, thost);
3443
3444     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3445
3446 #if FS_STATS_DETAILED
3447     FT_GetTimeOfDay(&opStopTime, 0);
3448     if (code == 0) {
3449         FS_LOCK;
3450         (opP->numSuccesses)++;
3451         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3452         fs_stats_AddTo((opP->sumTime), elapsedTime);
3453         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3454         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3455             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3456         }
3457         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3458             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3459         }
3460         FS_UNLOCK;
3461     }
3462 #endif /* FS_STATS_DETAILED */
3463
3464     osi_auditU(acall, StoreStatusEvent, code, 
3465                AUD_ID, t_client ? t_client->ViceId : 0,
3466                AUD_FID, Fid, AUD_END);
3467     return code;
3468
3469 }                               /*SRXAFS_StoreStatus */
3470
3471
3472 /*
3473  * This routine is called exclusively by SRXAFS_RemoveFile(), and should be
3474  * merged in when possible.
3475  */
3476 static afs_int32
3477 SAFSS_RemoveFile(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
3478                  struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
3479 {
3480     Vnode *parentptr = 0;       /* vnode of input Directory */
3481     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
3482     Vnode *targetptr = 0;       /* file to be deleted */
3483     Volume *volptr = 0;         /* pointer to the volume header */
3484     AFSFid fileFid;             /* area for Fid from the directory */
3485     Error errorCode = 0;                /* error code */
3486     DirHandle dir;              /* Handle for dir package I/O */
3487     struct client *client = 0;  /* pointer to client structure */
3488     afs_int32 rights, anyrights;        /* rights for this and any user */
3489     struct client *t_client;    /* tmp ptr to client data */
3490     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3491     struct rx_connection *tcon = rx_ConnectionOf(acall);
3492
3493     FidZero(&dir);
3494     /* Get ptr to client data for user Id for logging */
3495     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3496     logHostAddr.s_addr = rxr_HostOf(tcon);
3497     ViceLog(1,
3498             ("SAFS_RemoveFile %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
3499              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3500              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3501     FS_LOCK;
3502     AFSCallStats.RemoveFile++, AFSCallStats.TotalCalls++;
3503     FS_UNLOCK;
3504     /*
3505      * Get volume/vnode for the parent dir; caller's access rights are
3506      * also returned
3507      */
3508     if ((errorCode =
3509          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
3510                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3511                           &rights, &anyrights))) {
3512         goto Bad_RemoveFile;
3513     }
3514     /* set volume synchronization information */
3515     SetVolumeSync(Sync, volptr);
3516
3517     /* Does the caller has delete (& write) access to the parent directory? */
3518     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
3519         goto Bad_RemoveFile;
3520     }
3521
3522     /* Actually delete the desired file */
3523     if ((errorCode =
3524          DeleteTarget(parentptr, volptr, &targetptr, &dir, &fileFid, Name,
3525                       MustNOTBeDIR))) {
3526         goto Bad_RemoveFile;
3527     }
3528
3529     /* Update the vnode status of the parent dir */
3530 #if FS_STATS_DETAILED
3531     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3532                              parentptr->disk.linkCount,
3533                              client->InSameNetwork);
3534 #else
3535     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3536                              parentptr->disk.linkCount);
3537 #endif /* FS_STATS_DETAILED */
3538
3539     /* Return the updated parent dir's status back to caller */
3540     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
3541
3542     /* Handle internal callback state for the parent and the deleted file */
3543     if (targetptr->disk.linkCount == 0) {
3544         /* no references left, discard entry */
3545         DeleteFileCallBacks(&fileFid);
3546         /* convert the parent lock to a read lock before breaking callbacks */
3547         VVnodeWriteToRead(&errorCode, parentptr);
3548         assert(!errorCode || errorCode == VSALVAGE);
3549     } else {
3550         /* convert the parent lock to a read lock before breaking callbacks */
3551         VVnodeWriteToRead(&errorCode, parentptr);
3552         assert(!errorCode || errorCode == VSALVAGE);
3553         /* convert the target lock to a read lock before breaking callbacks */
3554         VVnodeWriteToRead(&errorCode, targetptr);
3555         assert(!errorCode || errorCode == VSALVAGE);
3556         /* tell all the file has changed */
3557         BreakCallBack(client->host, &fileFid, 1);
3558     }
3559
3560     /* break call back on the directory */
3561     BreakCallBack(client->host, DirFid, 0);
3562
3563   Bad_RemoveFile:
3564     /* Update and store volume/vnode and parent vnodes back */
3565     PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr, 
3566                      volptr, &client);
3567     FidZap(&dir);
3568     ViceLog(2, ("SAFS_RemoveFile returns %d\n", errorCode));
3569     return errorCode;
3570
3571 }                               /*SAFSS_RemoveFile */
3572
3573
3574 afs_int32
3575 SRXAFS_RemoveFile(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
3576                   struct AFSFetchStatus * OutDirStatus,
3577                   struct AFSVolSync * Sync)
3578 {
3579     afs_int32 code;
3580     struct rx_connection *tcon;
3581     struct host *thost;
3582     struct client *t_client = NULL;     /* tmp ptr to client data */
3583 #if FS_STATS_DETAILED
3584     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3585     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3586     struct timeval elapsedTime; /* Transfer time */
3587
3588     /*
3589      * Set our stats pointer, remember when the RPC operation started, and
3590      * tally the operation.
3591      */
3592     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_REMOVEFILE]);
3593     FS_LOCK;
3594     (opP->numOps)++;
3595     FS_UNLOCK;
3596     FT_GetTimeOfDay(&opStartTime, 0);
3597 #endif /* FS_STATS_DETAILED */
3598
3599     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3600         goto Bad_RemoveFile;
3601
3602     code = SAFSS_RemoveFile(acall, DirFid, Name, OutDirStatus, Sync);
3603
3604   Bad_RemoveFile:
3605     code = CallPostamble(tcon, code, thost);
3606
3607     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3608
3609 #if FS_STATS_DETAILED
3610     FT_GetTimeOfDay(&opStopTime, 0);
3611     if (code == 0) {
3612         FS_LOCK;
3613         (opP->numSuccesses)++;
3614         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3615         fs_stats_AddTo((opP->sumTime), elapsedTime);
3616         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3617         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3618             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3619         }
3620         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3621             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3622         }
3623         FS_UNLOCK;
3624     }
3625 #endif /* FS_STATS_DETAILED */
3626
3627     osi_auditU(acall, RemoveFileEvent, code, 
3628                AUD_ID, t_client ? t_client->ViceId : 0,
3629                AUD_FID, DirFid, AUD_STR, Name, AUD_END);
3630     return code;
3631
3632 }                               /*SRXAFS_RemoveFile */
3633
3634
3635 /*
3636  * This routine is called exclusively from SRXAFS_CreateFile(), and should
3637  * be merged in when possible.
3638  */
3639 static afs_int32
3640 SAFSS_CreateFile(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
3641                  struct AFSStoreStatus *InStatus, struct AFSFid *OutFid,
3642                  struct AFSFetchStatus *OutFidStatus,
3643                  struct AFSFetchStatus *OutDirStatus,
3644                  struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
3645 {
3646     Vnode *parentptr = 0;       /* vnode of input Directory */
3647     Vnode *targetptr = 0;       /* vnode of the new file */
3648     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
3649     Volume *volptr = 0;         /* pointer to the volume header */
3650     Error errorCode = 0;                /* error code */
3651     DirHandle dir;              /* Handle for dir package I/O */
3652     struct client *client = 0;  /* pointer to client structure */
3653     afs_int32 rights, anyrights;        /* rights for this and any user */
3654     struct client *t_client;    /* tmp ptr to client data */
3655     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3656     struct rx_connection *tcon = rx_ConnectionOf(acall);
3657
3658     FidZero(&dir);
3659
3660     /* Get ptr to client data for user Id for logging */
3661     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3662     logHostAddr.s_addr = rxr_HostOf(tcon);
3663     ViceLog(1,
3664             ("SAFS_CreateFile %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
3665              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3666              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3667     FS_LOCK;
3668     AFSCallStats.CreateFile++, AFSCallStats.TotalCalls++;
3669     FS_UNLOCK;
3670     if (!FileNameOK(Name)) {
3671         errorCode = EINVAL;
3672         goto Bad_CreateFile;
3673     }
3674
3675     /*
3676      * Get associated volume/vnode for the parent dir; caller long are
3677      * also returned
3678      */
3679     if ((errorCode =
3680          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
3681                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3682                           &rights, &anyrights))) {
3683         goto Bad_CreateFile;
3684     }
3685
3686     /* set volume synchronization information */
3687     SetVolumeSync(Sync, volptr);
3688
3689     /* Can we write (and insert) onto the parent directory? */
3690     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
3691         goto Bad_CreateFile;
3692     }
3693     /* get a new vnode for the file to be created and set it up */
3694     if ((errorCode =
3695          Alloc_NewVnode(parentptr, &dir, volptr, &targetptr, Name, OutFid,
3696                         vFile, nBlocks(0)))) {
3697         goto Bad_CreateFile;
3698     }
3699
3700     /* update the status of the parent vnode */
3701 #if FS_STATS_DETAILED
3702     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3703                              parentptr->disk.linkCount,
3704                              client->InSameNetwork);
3705 #else
3706     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3707                              parentptr->disk.linkCount);
3708 #endif /* FS_STATS_DETAILED */
3709
3710     /* update the status of the new file's vnode */
3711     Update_TargetVnodeStatus(targetptr, TVS_CFILE, client, InStatus,
3712                              parentptr, volptr, 0);
3713
3714     /* set up the return status for the parent dir and the newly created file, and since the newly created file is owned by the creator, give it PRSFS_ADMINISTER to tell the client its the owner of the file */
3715     GetStatus(targetptr, OutFidStatus, rights | PRSFS_ADMINISTER, anyrights, parentptr);
3716     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
3717
3718     /* convert the write lock to a read lock before breaking callbacks */
3719     VVnodeWriteToRead(&errorCode, parentptr);
3720     assert(!errorCode || errorCode == VSALVAGE);
3721
3722     /* break call back on parent dir */
3723     BreakCallBack(client->host, DirFid, 0);
3724
3725     /* Return a callback promise for the newly created file to the caller */
3726     SetCallBackStruct(AddCallBack(client->host, OutFid), CallBack);
3727
3728   Bad_CreateFile:
3729     /* Update and store volume/vnode and parent vnodes back */
3730     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
3731                            volptr, &client);
3732     FidZap(&dir);
3733     ViceLog(2, ("SAFS_CreateFile returns %d\n", errorCode));
3734     return errorCode;
3735
3736 }                               /*SAFSS_CreateFile */
3737
3738
3739 afs_int32
3740 SRXAFS_CreateFile(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
3741                   struct AFSStoreStatus * InStatus, struct AFSFid * OutFid,
3742                   struct AFSFetchStatus * OutFidStatus,
3743                   struct AFSFetchStatus * OutDirStatus,
3744                   struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
3745 {
3746     afs_int32 code;
3747     struct rx_connection *tcon;
3748     struct host *thost;
3749     struct client *t_client = NULL;     /* tmp ptr to client data */
3750 #if FS_STATS_DETAILED
3751     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3752     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3753     struct timeval elapsedTime; /* Transfer time */
3754
3755     /*
3756      * Set our stats pointer, remember when the RPC operation started, and
3757      * tally the operation.
3758      */
3759     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_CREATEFILE]);
3760     FS_LOCK;
3761     (opP->numOps)++;
3762     FS_UNLOCK;
3763     FT_GetTimeOfDay(&opStartTime, 0);
3764 #endif /* FS_STATS_DETAILED */
3765
3766     memset(OutFid, 0, sizeof(struct AFSFid));
3767
3768     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3769         goto Bad_CreateFile;
3770
3771     code =
3772         SAFSS_CreateFile(acall, DirFid, Name, InStatus, OutFid, OutFidStatus,
3773                          OutDirStatus, CallBack, Sync);
3774
3775   Bad_CreateFile:
3776     code = CallPostamble(tcon, code, thost);
3777
3778     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3779
3780 #if FS_STATS_DETAILED
3781     FT_GetTimeOfDay(&opStopTime, 0);
3782     if (code == 0) {
3783         FS_LOCK;
3784         (opP->numSuccesses)++;
3785         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3786         fs_stats_AddTo((opP->sumTime), elapsedTime);
3787         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3788         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3789             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3790         }
3791         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3792             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3793         }
3794         FS_UNLOCK;
3795     }
3796 #endif /* FS_STATS_DETAILED */
3797
3798     osi_auditU(acall, CreateFileEvent, code, 
3799                AUD_ID, t_client ? t_client->ViceId : 0,
3800                AUD_FID, DirFid, AUD_STR, Name, AUD_FID, OutFid, AUD_END);
3801     return code;
3802
3803 }                               /*SRXAFS_CreateFile */
3804
3805
3806 /*
3807  * This routine is called exclusively from SRXAFS_Rename(), and should be
3808  * merged in when possible.
3809  */
3810 static afs_int32
3811 SAFSS_Rename(struct rx_call *acall, struct AFSFid *OldDirFid, char *OldName,
3812              struct AFSFid *NewDirFid, char *NewName,
3813              struct AFSFetchStatus *OutOldDirStatus,
3814              struct AFSFetchStatus *OutNewDirStatus, struct AFSVolSync *Sync)
3815 {
3816     Vnode *oldvptr = 0;         /* vnode of the old Directory */
3817     Vnode *newvptr = 0;         /* vnode of the new Directory */
3818     Vnode *fileptr = 0;         /* vnode of the file to move */
3819     Vnode *newfileptr = 0;      /* vnode of the file to delete */
3820     Vnode *testvptr = 0;        /* used in directory tree walk */
3821     Vnode *parent = 0;          /* parent for use in SetAccessList */
3822     Error errorCode = 0;                /* error code */
3823     Error fileCode = 0;         /* used when writing Vnodes */
3824     VnodeId testnode;           /* used in directory tree walk */
3825     AFSFid fileFid;             /* Fid of file to move */
3826     AFSFid newFileFid;          /* Fid of new file */
3827     DirHandle olddir;           /* Handle for dir package I/O */
3828     DirHandle newdir;           /* Handle for dir package I/O */
3829     DirHandle filedir;          /* Handle for dir package I/O */
3830     DirHandle newfiledir;       /* Handle for dir package I/O */
3831     Volume *volptr = 0;         /* pointer to the volume header */
3832     struct client *client = 0;  /* pointer to client structure */
3833     afs_int32 rights, anyrights;        /* rights for this and any user */
3834     afs_int32 newrights;        /* rights for this user */
3835     afs_int32 newanyrights;     /* rights for any user */
3836     int doDelete;               /* deleted the rename target (ref count now 0) */
3837     int code;
3838     struct client *t_client;    /* tmp ptr to client data */
3839     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3840     struct rx_connection *tcon = rx_ConnectionOf(acall);
3841
3842     FidZero(&olddir);
3843     FidZero(&newdir);
3844     FidZero(&filedir);
3845     FidZero(&newfiledir);
3846
3847     /* Get ptr to client data for user Id for logging */
3848     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3849     logHostAddr.s_addr = rxr_HostOf(tcon);
3850     ViceLog(1,
3851             ("SAFS_Rename %s    to %s,  Fid = %u.%u.%u to %u.%u.%u, Host %s:%d, Id %d\n",
3852              OldName, NewName, OldDirFid->Volume, OldDirFid->Vnode,
3853              OldDirFid->Unique, NewDirFid->Volume, NewDirFid->Vnode,
3854              NewDirFid->Unique, inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3855     FS_LOCK;
3856     AFSCallStats.Rename++, AFSCallStats.TotalCalls++;
3857     FS_UNLOCK;
3858     if (!FileNameOK(NewName)) {
3859         errorCode = EINVAL;
3860         goto Bad_Rename;
3861     }
3862     if (OldDirFid->Volume != NewDirFid->Volume) {
3863         DFlush();
3864         errorCode = EXDEV;
3865         goto Bad_Rename;
3866     }
3867     if ((strcmp(OldName, ".") == 0) || (strcmp(OldName, "..") == 0)
3868         || (strcmp(NewName, ".") == 0) || (strcmp(NewName, "..") == 0)
3869         || (strlen(NewName) == 0) || (strlen(OldName) == 0)) {
3870         DFlush();
3871         errorCode = EINVAL;
3872         goto Bad_Rename;
3873     }
3874
3875     if (OldDirFid->Vnode <= NewDirFid->Vnode) {
3876         if ((errorCode =
3877              GetVolumePackage(tcon, OldDirFid, &volptr, &oldvptr, MustBeDIR,
3878                               &parent, &client, WRITE_LOCK, &rights,
3879                               &anyrights))) {
3880             DFlush();
3881             goto Bad_Rename;
3882         }
3883         if (OldDirFid->Vnode == NewDirFid->Vnode) {
3884             newvptr = oldvptr;
3885             newrights = rights, newanyrights = anyrights;
3886         } else
3887             if ((errorCode =
3888                  GetVolumePackage(tcon, NewDirFid, &volptr, &newvptr,
3889                                   MustBeDIR, &parent, &client, WRITE_LOCK,
3890                                   &newrights, &newanyrights))) {
3891             DFlush();
3892             goto Bad_Rename;
3893         }
3894     } else {
3895         if ((errorCode =
3896              GetVolumePackage(tcon, NewDirFid, &volptr, &newvptr, MustBeDIR,
3897                               &parent, &client, WRITE_LOCK, &newrights,
3898                               &newanyrights))) {
3899             DFlush();
3900             goto Bad_Rename;
3901         }
3902         if ((errorCode =
3903              GetVolumePackage(tcon, OldDirFid, &volptr, &oldvptr, MustBeDIR,
3904                               &parent, &client, WRITE_LOCK, &rights,
3905                               &anyrights))) {
3906             DFlush();
3907             goto Bad_Rename;
3908         }
3909     }
3910
3911     /* set volume synchronization information */
3912     SetVolumeSync(Sync, volptr);
3913
3914     if ((errorCode = CheckWriteMode(oldvptr, rights, PRSFS_DELETE))) {
3915         goto Bad_Rename;
3916     }
3917     if ((errorCode = CheckWriteMode(newvptr, newrights, PRSFS_INSERT))) {
3918         goto Bad_Rename;
3919     }
3920
3921     /* The CopyOnWrite might return ENOSPC ( disk full). Even if the second
3922      *  call to CopyOnWrite returns error, it is not necessary to revert back
3923      *  the effects of the first call because the contents of the volume is 
3924      *  not modified, it is only replicated.
3925      */
3926     if (oldvptr->disk.cloned) {
3927         ViceLog(25, ("Rename : calling CopyOnWrite on  old dir\n"));
3928         if ((errorCode = CopyOnWrite(oldvptr, volptr, 0, MAXFSIZE)))
3929             goto Bad_Rename;
3930     }
3931     SetDirHandle(&olddir, oldvptr);
3932     if (newvptr->disk.cloned) {
3933         ViceLog(25, ("Rename : calling CopyOnWrite on  new dir\n"));
3934         if ((errorCode = CopyOnWrite(newvptr, volptr, 0, MAXFSIZE)))
3935             goto Bad_Rename;
3936     }
3937
3938     SetDirHandle(&newdir, newvptr);
3939
3940     /* Lookup the file to delete its vnode */
3941     if (Lookup(&olddir, OldName, &fileFid)) {
3942         errorCode = ENOENT;
3943         goto Bad_Rename;
3944     }
3945     if (fileFid.Vnode == oldvptr->vnodeNumber
3946         || fileFid.Vnode == newvptr->vnodeNumber) {
3947         errorCode = FSERR_ELOOP;
3948         goto Bad_Rename;
3949     }
3950     fileFid.Volume = V_id(volptr);
3951     fileptr = VGetVnode(&errorCode, volptr, fileFid.Vnode, WRITE_LOCK);
3952     if (errorCode != 0) {
3953         ViceLog(0,
3954                 ("SAFSS_Rename(): Error in VGetVnode() for old file %s, code %d\n",
3955                  OldName, errorCode));
3956         VTakeOffline(volptr);
3957         goto Bad_Rename;
3958     }
3959     if (fileptr->disk.uniquifier != fileFid.Unique) {
3960         ViceLog(0,
3961                 ("SAFSS_Rename(): Old file %s uniquifier mismatch\n",
3962                  OldName));
3963         VTakeOffline(volptr);
3964         errorCode = EIO;
3965         goto Bad_Rename;
3966     }
3967
3968     if (fileptr->disk.type != vDirectory && oldvptr != newvptr
3969         && fileptr->disk.linkCount != 1) {
3970         /*
3971          * Hard links exist to this file - cannot move one of the links to
3972          * a new directory because of AFS restrictions (this is the same
3973          * reason that links cannot be made across directories, i.e.
3974          * access lists)
3975          */
3976         errorCode = EXDEV;
3977         goto Bad_Rename;
3978     }
3979
3980     /* Lookup the new file  */
3981     if (!(Lookup(&newdir, NewName, &newFileFid))) {
3982         if (readonlyServer) {
3983             errorCode = VREADONLY;
3984             goto Bad_Rename;
3985         }
3986         if (!(newrights & PRSFS_DELETE)) {
3987             errorCode = EACCES;
3988             goto Bad_Rename;
3989         }
3990         if (newFileFid.Vnode == oldvptr->vnodeNumber
3991             || newFileFid.Vnode == newvptr->vnodeNumber
3992             || newFileFid.Vnode == fileFid.Vnode) {
3993             errorCode = EINVAL;
3994             goto Bad_Rename;
3995         }
3996         newFileFid.Volume = V_id(volptr);
3997         newfileptr =
3998             VGetVnode(&errorCode, volptr, newFileFid.Vnode, WRITE_LOCK);
3999         if (errorCode != 0) {
4000             ViceLog(0,
4001                     ("SAFSS_Rename(): Error in VGetVnode() for new file %s, code %d\n",
4002                      NewName, errorCode));
4003             VTakeOffline(volptr);
4004             goto Bad_Rename;
4005         }
4006         if (fileptr->disk.uniquifier != fileFid.Unique) {
4007             ViceLog(0,
4008                     ("SAFSS_Rename(): New file %s uniquifier mismatch\n",
4009                      NewName));
4010             VTakeOffline(volptr);
4011             errorCode = EIO;
4012             goto Bad_Rename;
4013         }
4014         SetDirHandle(&newfiledir, newfileptr);
4015         /* Now check that we're moving directories over directories properly, etc.
4016          * return proper POSIX error codes:
4017          * if fileptr is a file and new is a dir: EISDIR.
4018          * if fileptr is a dir and new is a file: ENOTDIR.
4019          * Also, dir to be removed must be empty, of course.
4020          */
4021         if (newfileptr->disk.type == vDirectory) {
4022             if (fileptr->disk.type != vDirectory) {
4023                 errorCode = EISDIR;
4024                 goto Bad_Rename;
4025             }
4026             if ((IsEmpty(&newfiledir))) {
4027                 errorCode = EEXIST;
4028                 goto Bad_Rename;
4029             }
4030         } else {
4031             if (fileptr->disk.type == vDirectory) {
4032                 errorCode = ENOTDIR;
4033                 goto Bad_Rename;
4034             }
4035         }
4036     }
4037
4038     /*
4039      * ok - now we check that the old name is not above new name in the
4040      * directory structure.  This is to prevent removing a subtree alltogether
4041      */
4042     if ((oldvptr != newvptr) && (fileptr->disk.type == vDirectory)) {
4043         afs_int32 forpass = 0, vnum = 0, top = 0;
4044         for (testnode = newvptr->disk.parent; testnode != 0; forpass++) {
4045             if (testnode > vnum) vnum = testnode;
4046             if (forpass > vnum) {
4047                 errorCode = FSERR_ELOOP;
4048                 goto Bad_Rename;
4049             }
4050             if (testnode == oldvptr->vnodeNumber) {
4051                 testnode = oldvptr->disk.parent;
4052                 continue;
4053             }
4054             if ((testnode == fileptr->vnodeNumber)
4055                 || (testnode == newvptr->vnodeNumber)) {
4056                 errorCode = FSERR_ELOOP;
4057                 goto Bad_Rename;
4058             }
4059             if ((newfileptr) && (testnode == newfileptr->vnodeNumber)) {
4060                 errorCode = FSERR_ELOOP;
4061                 goto Bad_Rename;
4062             }
4063             if (testnode == 1) top = 1;
4064             testvptr = VGetVnode(&errorCode, volptr, testnode, READ_LOCK);
4065             assert(errorCode == 0);
4066             testnode = testvptr->disk.parent;
4067             VPutVnode(&errorCode, testvptr);
4068             if ((top == 1) && (testnode != 0)) {
4069                 VTakeOffline(volptr);
4070                 ViceLog(0,
4071                         ("Volume %u now offline, must be salvaged.\n",
4072                          volptr->hashid));
4073                 errorCode = EIO;
4074                 goto Bad_Rename;
4075             }
4076             assert(errorCode == 0);
4077         }
4078     }
4079     /* Do the CopyonWrite first before modifying anything else. Copying is
4080      *  required because we may have to change entries for .. 
4081      */
4082     if ((fileptr->disk.type == vDirectory) && (fileptr->disk.cloned)) {
4083         ViceLog(25, ("Rename : calling CopyOnWrite on  target dir\n"));
4084         if ((errorCode = CopyOnWrite(fileptr, volptr, 0, MAXFSIZE)))
4085             goto Bad_Rename;
4086     }
4087
4088     /* If the new name exists already, delete it and the file it points to */
4089     doDelete = 0;
4090     if (newfileptr) {
4091         /* Delete NewName from its directory */
4092         code = Delete(&newdir, NewName);
4093         assert(code == 0);
4094
4095         /* Drop the link count */
4096         newfileptr->disk.linkCount--;
4097         if (newfileptr->disk.linkCount == 0) {  /* Link count 0 - delete */
4098             afs_fsize_t newSize;
4099             VN_GET_LEN(newSize, newfileptr);
4100             VAdjustDiskUsage((Error *) & errorCode, volptr,
4101                              (afs_sfsize_t) - nBlocks(newSize), 0);
4102             if (VN_GET_INO(newfileptr)) {
4103                 IH_REALLYCLOSE(newfileptr->handle);
4104                 errorCode =
4105                     IH_DEC(V_linkHandle(volptr), VN_GET_INO(newfileptr),
4106                            V_parentId(volptr));
4107                 IH_RELEASE(newfileptr->handle);
4108                 if (errorCode == -1) {
4109                     ViceLog(0,
4110                             ("Del: inode=%s, name=%s, errno=%d\n",
4111                              PrintInode(NULL, VN_GET_INO(newfileptr)),
4112                              NewName, errno));
4113                     if ((errno != ENOENT) && (errno != EIO)
4114                         && (errno != ENXIO))
4115                         ViceLog(0, ("Do we need to fsck?"));
4116                 }
4117             }
4118             VN_SET_INO(newfileptr, (Inode) 0);
4119             newfileptr->delete = 1;     /* Mark NewName vnode to delete */
4120             doDelete = 1;
4121         } else {
4122             /* Link count did not drop to zero.
4123              * Mark NewName vnode as changed - updates stime.
4124              */
4125             newfileptr->changed_newTime = 1;
4126         }
4127     }
4128
4129     /*
4130      * If the create below fails, and the delete above worked, we have
4131      * removed the new name and not replaced it.  This is not very likely,
4132      * but possible.  We could try to put the old file back, but it is
4133      * highly unlikely that it would work since it would involve issuing
4134      * another create.
4135      */
4136     if ((errorCode = Create(&newdir, (char *)NewName, &fileFid)))
4137         goto Bad_Rename;
4138
4139     /* Delete the old name */
4140     assert(Delete(&olddir, (char *)OldName) == 0);
4141
4142     /* if the directory length changes, reflect it in the statistics */
4143 #if FS_STATS_DETAILED
4144     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
4145                              oldvptr->disk.linkCount, client->InSameNetwork);
4146     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
4147                              newvptr->disk.linkCount, client->InSameNetwork);
4148 #else
4149     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
4150                              oldvptr->disk.linkCount);
4151     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
4152                              newvptr->disk.linkCount);
4153 #endif /* FS_STATS_DETAILED */
4154
4155     if (oldvptr == newvptr)
4156         oldvptr->disk.dataVersion--;    /* Since it was bumped by 2! */
4157
4158     fileptr->disk.parent = newvptr->vnodeNumber;
4159     fileptr->changed_newTime = 1;       /* status change of moved file */
4160
4161     /* if we are dealing with a rename of a directory */
4162     if (fileptr->disk.type == vDirectory) {
4163         assert(!fileptr->disk.cloned);
4164         SetDirHandle(&filedir, fileptr);
4165         /* fix .. to point to the correct place */
4166         Delete(&filedir, ".."); /* No assert--some directories may be bad */
4167         assert(Create(&filedir, "..", NewDirFid) == 0);
4168         fileptr->disk.dataVersion++;
4169         /* if the parent directories are different the link counts have to be   */
4170         /* changed due to .. in the renamed directory */
4171         if (oldvptr != newvptr) {
4172             oldvptr->disk.linkCount--;
4173             newvptr->disk.linkCount++;
4174         }
4175     }
4176
4177     /* set up return status */
4178     GetStatus(oldvptr, OutOldDirStatus, rights, anyrights, 0);
4179     GetStatus(newvptr, OutNewDirStatus, newrights, newanyrights, 0);
4180     if (newfileptr && doDelete) {
4181         DeleteFileCallBacks(&newFileFid);       /* no other references */
4182     }
4183
4184     DFlush();
4185
4186     /* convert the write locks to a read locks before breaking callbacks */
4187     VVnodeWriteToRead(&errorCode, newvptr);
4188     assert(!errorCode || errorCode == VSALVAGE);
4189     if (oldvptr != newvptr) {
4190         VVnodeWriteToRead(&errorCode, oldvptr);
4191         assert(!errorCode || errorCode == VSALVAGE);
4192     }
4193     if (newfileptr && !doDelete) {
4194         /* convert the write lock to a read lock before breaking callbacks */
4195         VVnodeWriteToRead(&errorCode, newfileptr);
4196         assert(!errorCode || errorCode == VSALVAGE);
4197     }
4198
4199     /* break call back on NewDirFid, OldDirFid, NewDirFid and newFileFid  */
4200     BreakCallBack(client->host, NewDirFid, 0);
4201     if (oldvptr != newvptr) {
4202         BreakCallBack(client->host, OldDirFid, 0);
4203         if (fileptr->disk.type == vDirectory)   /* if a dir moved, .. changed */
4204             BreakCallBack(client->host, &fileFid, 0);
4205     }
4206     if (newfileptr) {
4207         /* Note:  it is not necessary to break the callback */
4208         if (doDelete)
4209             DeleteFileCallBacks(&newFileFid);   /* no other references */
4210         else
4211             /* other's still exist (with wrong link count) */
4212             BreakCallBack(client->host, &newFileFid, 1);
4213     }
4214
4215   Bad_Rename:
4216     if (newfileptr) {
4217         VPutVnode(&fileCode, newfileptr);
4218         assert(fileCode == 0);
4219     }
4220     (void)PutVolumePackage(fileptr, (newvptr && newvptr != oldvptr ? 
4221                                      newvptr : 0), oldvptr, volptr, &client);
4222     FidZap(&olddir);
4223     FidZap(&newdir);
4224     FidZap(&filedir);
4225     FidZap(&newfiledir);
4226     ViceLog(2, ("SAFS_Rename returns %d\n", errorCode));
4227     return errorCode;
4228
4229 }                               /*SAFSS_Rename */
4230
4231
4232 afs_int32
4233 SRXAFS_Rename(struct rx_call * acall, struct AFSFid * OldDirFid,
4234               char *OldName, struct AFSFid * NewDirFid, char *NewName,
4235               struct AFSFetchStatus * OutOldDirStatus,
4236               struct AFSFetchStatus * OutNewDirStatus,
4237               struct AFSVolSync * Sync)
4238 {
4239     afs_int32 code;
4240     struct rx_connection *tcon;
4241     struct host *thost;
4242     struct client *t_client = NULL;     /* tmp ptr to client data */
4243 #if FS_STATS_DETAILED
4244     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4245     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4246     struct timeval elapsedTime; /* Transfer time */
4247
4248     /*
4249      * Set our stats pointer, remember when the RPC operation started, and
4250      * tally the operation.
4251      */
4252     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_RENAME]);
4253     FS_LOCK;
4254     (opP->numOps)++;
4255     FS_UNLOCK;
4256     FT_GetTimeOfDay(&opStartTime, 0);
4257 #endif /* FS_STATS_DETAILED */
4258
4259     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4260         goto Bad_Rename;
4261
4262     code =
4263         SAFSS_Rename(acall, OldDirFid, OldName, NewDirFid, NewName,
4264                      OutOldDirStatus, OutNewDirStatus, Sync);
4265
4266   Bad_Rename:
4267     code = CallPostamble(tcon, code, thost);
4268
4269     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4270
4271 #if FS_STATS_DETAILED
4272     FT_GetTimeOfDay(&opStopTime, 0);
4273     if (code == 0) {
4274         FS_LOCK;
4275         (opP->numSuccesses)++;
4276         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4277         fs_stats_AddTo((opP->sumTime), elapsedTime);
4278         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4279         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4280             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4281         }
4282         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4283             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4284         }
4285         FS_UNLOCK;
4286     }
4287 #endif /* FS_STATS_DETAILED */
4288
4289     osi_auditU(acall, RenameFileEvent, code, 
4290                AUD_ID, t_client ? t_client->ViceId : 0,
4291                AUD_FID, OldDirFid, AUD_STR, OldName, 
4292                AUD_FID, NewDirFid, AUD_STR, NewName, AUD_END);
4293     return code;
4294
4295 }                               /*SRXAFS_Rename */
4296
4297
4298 /*
4299  * This routine is called exclusively by SRXAFS_Symlink(), and should be
4300  * merged into it when possible.
4301  */
4302 static afs_int32
4303 SAFSS_Symlink(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4304               char *LinkContents, struct AFSStoreStatus *InStatus,
4305               struct AFSFid *OutFid, struct AFSFetchStatus *OutFidStatus,
4306               struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4307 {
4308     Vnode *parentptr = 0;       /* vnode of input Directory */
4309     Vnode *targetptr = 0;       /* vnode of the new link */
4310     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4311     Error errorCode = 0;                /* error code */
4312     int len, code = 0;
4313     DirHandle dir;              /* Handle for dir package I/O */
4314     Volume *volptr = 0;         /* pointer to the volume header */
4315     struct client *client = 0;  /* pointer to client structure */
4316     afs_int32 rights, anyrights;        /* rights for this and any user */
4317     struct client *t_client;    /* tmp ptr to client data */
4318     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4319     FdHandle_t *fdP;
4320     struct rx_connection *tcon = rx_ConnectionOf(acall);
4321
4322     FidZero(&dir);
4323
4324     /* Get ptr to client data for user Id for logging */
4325     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4326     logHostAddr.s_addr = rxr_HostOf(tcon);
4327     ViceLog(1,
4328             ("SAFS_Symlink %s to %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4329              LinkContents, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4330              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4331     FS_LOCK;
4332     AFSCallStats.Symlink++, AFSCallStats.TotalCalls++;
4333     FS_UNLOCK;
4334     if (!FileNameOK(Name)) {
4335         errorCode = EINVAL;
4336         goto Bad_SymLink;
4337     }
4338
4339     /*
4340      * Get the vnode and volume for the parent dir along with the caller's
4341      * rights to it
4342      */
4343     if ((errorCode =
4344          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4345                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4346                           &rights, &anyrights))) {
4347         goto Bad_SymLink;
4348     }
4349
4350     /* set volume synchronization information */
4351     SetVolumeSync(Sync, volptr);
4352
4353     /* Does the caller has insert (and write) access to the parent directory? */
4354     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4355         goto Bad_SymLink;
4356     }
4357
4358     /*
4359      * If we're creating a mount point (any x bits clear), we must have
4360      * administer access to the directory, too.  Always allow sysadmins
4361      * to do this.
4362      */
4363     if ((InStatus->Mask & AFS_SETMODE) && !(InStatus->UnixModeBits & 0111)) {
4364         if (readonlyServer) {
4365             errorCode = VREADONLY;
4366             goto Bad_SymLink;
4367         }
4368         /*
4369          * We have a mountpoint, 'cause we're trying to set the Unix mode
4370          * bits to something with some x bits missing (default mode bits
4371          * if AFS_SETMODE is false is 0777)
4372          */
4373         if (VanillaUser(client) && !(rights & PRSFS_ADMINISTER)) {
4374             errorCode = EACCES;
4375             goto Bad_SymLink;
4376         }
4377     }
4378
4379     /* get a new vnode for the symlink and set it up */
4380     if ((errorCode =
4381          Alloc_NewVnode(parentptr, &dir, volptr, &targetptr, Name, OutFid,
4382                         vSymlink, nBlocks(strlen((char *)LinkContents))))) {
4383         goto Bad_SymLink;
4384     }
4385
4386     /* update the status of the parent vnode */
4387 #if FS_STATS_DETAILED
4388     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4389                              parentptr->disk.linkCount,
4390                              client->InSameNetwork);
4391 #else
4392     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4393                              parentptr->disk.linkCount);
4394 #endif /* FS_STATS_DETAILED */
4395
4396     /* update the status of the new symbolic link file vnode */
4397     Update_TargetVnodeStatus(targetptr, TVS_SLINK, client, InStatus,
4398                              parentptr, volptr, strlen((char *)LinkContents));
4399
4400     /* Write the contents of the symbolic link name into the target inode */
4401     fdP = IH_OPEN(targetptr->handle);
4402     if (fdP == NULL) {
4403         (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4404                                volptr, &client);
4405         VTakeOffline(volptr);
4406         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
4407                     volptr->hashid));
4408         return EIO;
4409     }    
4410     len = strlen((char *) LinkContents);
4411     code = (len == FDH_WRITE(fdP, (char *) LinkContents, len)) ? 0 : VDISKFULL;
4412     if (code) 
4413         ViceLog(0, ("SAFSS_Symlink FDH_WRITE failed for len=%d, Fid=%u.%d.%d\n", len, OutFid->Volume, OutFid->Vnode, OutFid->Unique));
4414     FDH_CLOSE(fdP);
4415     /*
4416      * Set up and return modified status for the parent dir and new symlink
4417      * to caller.
4418      */
4419     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4420     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4421
4422     /* convert the write lock to a read lock before breaking callbacks */
4423     VVnodeWriteToRead(&errorCode, parentptr);
4424     assert(!errorCode || errorCode == VSALVAGE);
4425
4426     /* break call back on the parent dir */
4427     BreakCallBack(client->host, DirFid, 0);
4428
4429   Bad_SymLink:
4430     /* Write the all modified vnodes (parent, new files) and volume back */
4431     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4432                            volptr, &client);
4433     FidZap(&dir);
4434     ViceLog(2, ("SAFS_Symlink returns %d\n", errorCode));
4435     return ( errorCode ? errorCode : code );
4436
4437 }                               /*SAFSS_Symlink */
4438
4439
4440 afs_int32
4441 SRXAFS_Symlink(struct rx_call *acall,   /* Rx call */
4442                struct AFSFid *DirFid,   /* Parent dir's fid */
4443                char *Name,              /* File name to create */
4444                char *LinkContents,      /* Contents of the new created file */
4445                struct AFSStoreStatus *InStatus, /* Input status for the new symbolic link */
4446                struct AFSFid *OutFid,   /* Fid for newly created symbolic link */
4447                struct AFSFetchStatus *OutFidStatus,     /* Output status for new symbolic link */
4448                struct AFSFetchStatus *OutDirStatus,     /* Output status for parent dir */
4449                struct AFSVolSync *Sync)
4450 {
4451     afs_int32 code;
4452     struct rx_connection *tcon;
4453     struct host *thost;
4454     struct client *t_client = NULL;     /* tmp ptr to client data */
4455 #if FS_STATS_DETAILED
4456     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4457     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4458     struct timeval elapsedTime; /* Transfer time */
4459
4460     /*
4461      * Set our stats pointer, remember when the RPC operation started, and
4462      * tally the operation.
4463      */
4464     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SYMLINK]);
4465     FS_LOCK;
4466     (opP->numOps)++;
4467     FS_UNLOCK;
4468     FT_GetTimeOfDay(&opStartTime, 0);
4469 #endif /* FS_STATS_DETAILED */
4470
4471     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4472         goto Bad_Symlink;
4473
4474     code =
4475         SAFSS_Symlink(acall, DirFid, Name, LinkContents, InStatus, OutFid,
4476                       OutFidStatus, OutDirStatus, Sync);
4477
4478   Bad_Symlink:
4479     code = CallPostamble(tcon, code, thost);
4480
4481     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4482
4483 #if FS_STATS_DETAILED
4484     FT_GetTimeOfDay(&opStopTime, 0);
4485     if (code == 0) {
4486         FS_LOCK;
4487         (opP->numSuccesses)++;
4488         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4489         fs_stats_AddTo((opP->sumTime), elapsedTime);
4490         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4491         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4492             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4493         }
4494         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4495             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4496         }
4497         FS_UNLOCK;
4498     }
4499 #endif /* FS_STATS_DETAILED */
4500
4501     osi_auditU(acall, SymlinkEvent, code, 
4502                AUD_ID, t_client ? t_client->ViceId : 0, 
4503                AUD_FID, DirFid, AUD_STR, Name,
4504                AUD_FID, OutFid, AUD_STR, LinkContents, AUD_END);
4505     return code;
4506
4507 }                               /*SRXAFS_Symlink */
4508
4509
4510 /*
4511  * This routine is called exclusively by SRXAFS_Link(), and should be
4512  * merged into it when possible.
4513  */
4514 static afs_int32
4515 SAFSS_Link(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4516            struct AFSFid *ExistingFid, struct AFSFetchStatus *OutFidStatus,
4517            struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4518 {
4519     Vnode *parentptr = 0;       /* vnode of input Directory */
4520     Vnode *targetptr = 0;       /* vnode of the new file */
4521     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4522     Volume *volptr = 0;         /* pointer to the volume header */
4523     Error errorCode = 0;                /* error code */
4524     DirHandle dir;              /* Handle for dir package I/O */
4525     struct client *client = 0;  /* pointer to client structure */
4526     afs_int32 rights, anyrights;        /* rights for this and any user */
4527     struct client *t_client;    /* tmp ptr to client data */
4528     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4529     struct rx_connection *tcon = rx_ConnectionOf(acall);
4530
4531     FidZero(&dir);
4532
4533     /* Get ptr to client data for user Id for logging */
4534     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4535     logHostAddr.s_addr = rxr_HostOf(tcon);
4536     ViceLog(1,
4537             ("SAFS_Link %s,     Did = %u.%u.%u, Fid = %u.%u.%u, Host %s:%d, Id %d\n",
4538              Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4539              ExistingFid->Volume, ExistingFid->Vnode, ExistingFid->Unique,
4540              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4541     FS_LOCK;
4542     AFSCallStats.Link++, AFSCallStats.TotalCalls++;
4543     FS_UNLOCK;
4544     if (DirFid->Volume != ExistingFid->Volume) {
4545         errorCode = EXDEV;
4546         goto Bad_Link;
4547     }
4548     if (!FileNameOK(Name)) {
4549         errorCode = EINVAL;
4550         goto Bad_Link;
4551     }
4552
4553     /*
4554      * Get the vnode and volume for the parent dir along with the caller's
4555      * rights to it
4556      */
4557     if ((errorCode =
4558          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4559                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4560                           &rights, &anyrights))) {
4561         goto Bad_Link;
4562     }
4563
4564     /* set volume synchronization information */
4565     SetVolumeSync(Sync, volptr);
4566
4567     /* Can the caller insert into the parent directory? */
4568     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4569         goto Bad_Link;
4570     }
4571
4572     if (((DirFid->Vnode & 1) && (ExistingFid->Vnode & 1)) || (DirFid->Vnode == ExistingFid->Vnode)) {   /* at present, */
4573         /* AFS fileservers always have directory vnodes that are odd.   */
4574         errorCode = EISDIR;
4575         goto Bad_Link;
4576     }
4577
4578     /* get the file vnode  */
4579     if ((errorCode =
4580          CheckVnode(ExistingFid, &volptr, &targetptr, WRITE_LOCK))) {
4581         goto Bad_Link;
4582     }
4583     if (targetptr->disk.type != vFile) {
4584         errorCode = EISDIR;
4585         goto Bad_Link;
4586     }
4587     if (targetptr->disk.parent != DirFid->Vnode) {
4588         errorCode = EXDEV;
4589         goto Bad_Link;
4590     }
4591     if (parentptr->disk.cloned) {
4592         ViceLog(25, ("Link : calling CopyOnWrite on  target dir\n"));
4593         if ((errorCode = CopyOnWrite(parentptr, volptr, 0, MAXFSIZE)))
4594             goto Bad_Link;      /* disk full error */
4595     }
4596
4597     /* add the name to the directory */
4598     SetDirHandle(&dir, parentptr);
4599     if ((errorCode = Create(&dir, (char *)Name, ExistingFid)))
4600         goto Bad_Link;
4601     DFlush();
4602
4603     /* update the status in the parent vnode */
4604     /**WARNING** --> disk.author SHOULDN'T be modified???? */
4605 #if FS_STATS_DETAILED
4606     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4607                              parentptr->disk.linkCount,
4608                              client->InSameNetwork);
4609 #else
4610     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4611                              parentptr->disk.linkCount);
4612 #endif /* FS_STATS_DETAILED */
4613
4614     targetptr->disk.linkCount++;
4615     targetptr->disk.author = client->ViceId;
4616     targetptr->changed_newTime = 1;     /* Status change of linked-to file */
4617
4618     /* set up return status */
4619     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4620     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4621
4622     /* convert the write locks to read locks before breaking callbacks */
4623     VVnodeWriteToRead(&errorCode, targetptr);
4624     assert(!errorCode || errorCode == VSALVAGE);
4625     VVnodeWriteToRead(&errorCode, parentptr);
4626     assert(!errorCode || errorCode == VSALVAGE);
4627
4628     /* break call back on DirFid */
4629     BreakCallBack(client->host, DirFid, 0);
4630     /*
4631      * We also need to break the callback for the file that is hard-linked since part 
4632      * of its status (like linkcount) is changed
4633      */
4634     BreakCallBack(client->host, ExistingFid, 0);
4635
4636   Bad_Link:
4637     /* Write the all modified vnodes (parent, new files) and volume back */
4638     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4639                            volptr, &client);
4640     FidZap(&dir);
4641     ViceLog(2, ("SAFS_Link returns %d\n", errorCode));
4642     return errorCode;
4643
4644 }                               /*SAFSS_Link */
4645
4646
4647 afs_int32
4648 SRXAFS_Link(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4649             struct AFSFid * ExistingFid, struct AFSFetchStatus * OutFidStatus,
4650             struct AFSFetchStatus * OutDirStatus, struct AFSVolSync * Sync)
4651 {
4652     afs_int32 code;
4653     struct rx_connection *tcon;
4654     struct host *thost;
4655     struct client *t_client = NULL;     /* tmp ptr to client data */
4656 #if FS_STATS_DETAILED
4657     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4658     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4659     struct timeval elapsedTime; /* Transfer time */
4660
4661     /*
4662      * Set our stats pointer, remember when the RPC operation started, and
4663      * tally the operation.
4664      */
4665     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_LINK]);
4666     FS_LOCK;
4667     (opP->numOps)++;
4668     FS_UNLOCK;
4669     FT_GetTimeOfDay(&opStartTime, 0);
4670 #endif /* FS_STATS_DETAILED */
4671
4672     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4673         goto Bad_Link;
4674
4675     code =
4676         SAFSS_Link(acall, DirFid, Name, ExistingFid, OutFidStatus,
4677                    OutDirStatus, Sync);
4678
4679   Bad_Link:
4680     code = CallPostamble(tcon, code, thost);
4681
4682     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4683
4684 #if FS_STATS_DETAILED
4685     FT_GetTimeOfDay(&opStopTime, 0);
4686     if (code == 0) {
4687         FS_LOCK;
4688         (opP->numSuccesses)++;
4689         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4690         fs_stats_AddTo((opP->sumTime), elapsedTime);
4691         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4692         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4693             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4694         }
4695         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4696             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4697         }
4698         FS_UNLOCK;
4699     }
4700 #endif /* FS_STATS_DETAILED */
4701
4702     osi_auditU(acall, LinkEvent, code, 
4703                AUD_ID, t_client ? t_client->ViceId : 0,
4704                AUD_FID, DirFid, AUD_STR, Name,
4705                AUD_FID, ExistingFid, AUD_END);
4706     return code;
4707
4708 }                               /*SRXAFS_Link */
4709
4710
4711 /*
4712  * This routine is called exclusively by SRXAFS_MakeDir(), and should be
4713  * merged into it when possible.
4714  */
4715 static afs_int32
4716 SAFSS_MakeDir(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4717               struct AFSStoreStatus *InStatus, struct AFSFid *OutFid,
4718               struct AFSFetchStatus *OutFidStatus,
4719               struct AFSFetchStatus *OutDirStatus,
4720               struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
4721 {
4722     Vnode *parentptr = 0;       /* vnode of input Directory */
4723     Vnode *targetptr = 0;       /* vnode of the new file */
4724     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4725     Volume *volptr = 0;         /* pointer to the volume header */
4726     Error errorCode = 0;                /* error code */
4727     struct acl_accessList *newACL;      /* Access list */
4728     int newACLSize;             /* Size of access list */
4729     DirHandle dir;              /* Handle for dir package I/O */
4730     DirHandle parentdir;        /* Handle for dir package I/O */
4731     struct client *client = 0;  /* pointer to client structure */
4732     afs_int32 rights, anyrights;        /* rights for this and any user */
4733     struct client *t_client;    /* tmp ptr to client data */
4734     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4735     struct rx_connection *tcon = rx_ConnectionOf(acall);
4736
4737     FidZero(&dir);
4738     FidZero(&parentdir);
4739
4740     /* Get ptr to client data for user Id for logging */
4741     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4742     logHostAddr.s_addr = rxr_HostOf(tcon);
4743     ViceLog(1,
4744             ("SAFS_MakeDir %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4745              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4746              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4747     FS_LOCK;
4748     AFSCallStats.MakeDir++, AFSCallStats.TotalCalls++;
4749     FS_UNLOCK;
4750     if (!FileNameOK(Name)) {
4751         errorCode = EINVAL;
4752         goto Bad_MakeDir;
4753     }
4754
4755     /*
4756      * Get the vnode and volume for the parent dir along with the caller's
4757      * rights to it.
4758      */
4759     if ((errorCode =
4760          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4761                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4762                           &rights, &anyrights))) {
4763         goto Bad_MakeDir;
4764     }
4765
4766     /* set volume synchronization information */
4767     SetVolumeSync(Sync, volptr);
4768
4769     /* Write access to the parent directory? */
4770 #ifdef DIRCREATE_NEED_WRITE
4771     /*
4772      * requires w access for the user to create a directory. this
4773      * closes a loophole in the current security arrangement, since a
4774      * user with i access only can create a directory and get the
4775      * implcit a access that goes with dir ownership, and proceed to 
4776      * subvert quota in the volume.
4777      */
4778     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))
4779         || (errorCode = CheckWriteMode(parentptr, rights, PRSFS_WRITE))) {
4780 #else
4781     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4782 #endif /* DIRCREATE_NEED_WRITE */
4783         goto Bad_MakeDir;
4784     }
4785 #define EMPTYDIRBLOCKS 2
4786     /* get a new vnode and set it up */
4787     if ((errorCode =
4788          Alloc_NewVnode(parentptr, &parentdir, volptr, &targetptr, Name,
4789                         OutFid, vDirectory, EMPTYDIRBLOCKS))) {
4790         goto Bad_MakeDir;
4791     }
4792
4793     /* Update the status for the parent dir */
4794 #if FS_STATS_DETAILED
4795     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4796                              parentptr->disk.linkCount + 1,
4797                              client->InSameNetwork);
4798 #else
4799     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4800                              parentptr->disk.linkCount + 1);
4801 #endif /* FS_STATS_DETAILED */
4802
4803     /* Point to target's ACL buffer and copy the parent's ACL contents to it */
4804     assert((SetAccessList
4805             (&targetptr, &volptr, &newACL, &newACLSize,
4806              &parentwhentargetnotdir, (AFSFid *) 0, 0)) == 0);
4807     assert(parentwhentargetnotdir == 0);
4808     memcpy((char *)newACL, (char *)VVnodeACL(parentptr), VAclSize(parentptr));
4809
4810     /* update the status for the target vnode */
4811     Update_TargetVnodeStatus(targetptr, TVS_MKDIR, client, InStatus,
4812                              parentptr, volptr, 0);
4813
4814     /* Actually create the New directory in the directory package */
4815     SetDirHandle(&dir, targetptr);
4816     assert(!(MakeDir(&dir, (afs_int32 *)OutFid, (afs_int32 *)DirFid)));
4817     DFlush();
4818     VN_SET_LEN(targetptr, (afs_fsize_t) Length(&dir));
4819
4820     /* set up return status */
4821     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4822     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4823
4824     /* convert the write lock to a read lock before breaking callbacks */
4825     VVnodeWriteToRead(&errorCode, parentptr);
4826     assert(!errorCode || errorCode == VSALVAGE);
4827
4828     /* break call back on DirFid */
4829     BreakCallBack(client->host, DirFid, 0);
4830
4831     /* Return a callback promise to caller */
4832     SetCallBackStruct(AddCallBack(client->host, OutFid), CallBack);
4833
4834   Bad_MakeDir:
4835     /* Write the all modified vnodes (parent, new files) and volume back */
4836     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4837                            volptr, &client);
4838     FidZap(&dir);
4839     FidZap(&parentdir);
4840     ViceLog(2, ("SAFS_MakeDir returns %d\n", errorCode));
4841     return errorCode;
4842
4843 }                               /*SAFSS_MakeDir */
4844
4845
4846 afs_int32
4847 SRXAFS_MakeDir(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4848                struct AFSStoreStatus * InStatus, struct AFSFid * OutFid,
4849                struct AFSFetchStatus * OutFidStatus,
4850                struct AFSFetchStatus * OutDirStatus,
4851                struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
4852 {
4853     afs_int32 code;
4854     struct rx_connection *tcon;
4855     struct host *thost;
4856     struct client *t_client = NULL;     /* tmp ptr to client data */
4857 #if FS_STATS_DETAILED
4858     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4859     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4860     struct timeval elapsedTime; /* Transfer time */
4861
4862     /*
4863      * Set our stats pointer, remember when the RPC operation started, and
4864      * tally the operation.
4865      */
4866     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_MAKEDIR]);
4867     FS_LOCK;
4868     (opP->numOps)++;
4869     FS_UNLOCK;
4870     FT_GetTimeOfDay(&opStartTime, 0);
4871 #endif /* FS_STATS_DETAILED */
4872     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4873         goto Bad_MakeDir;
4874
4875     code =
4876         SAFSS_MakeDir(acall, DirFid, Name, InStatus, OutFid, OutFidStatus,
4877                       OutDirStatus, CallBack, Sync);
4878
4879   Bad_MakeDir:
4880     code = CallPostamble(tcon, code, thost);
4881
4882     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4883
4884 #if FS_STATS_DETAILED
4885     FT_GetTimeOfDay(&opStopTime, 0);
4886     if (code == 0) {
4887         FS_LOCK;
4888         (opP->numSuccesses)++;
4889         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4890         fs_stats_AddTo((opP->sumTime), elapsedTime);
4891         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4892         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4893             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4894         }
4895         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4896             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4897         }
4898         FS_UNLOCK;
4899     }
4900 #endif /* FS_STATS_DETAILED */
4901
4902     osi_auditU(acall, MakeDirEvent, code, 
4903                AUD_ID, t_client ? t_client->ViceId : 0,
4904                AUD_FID, DirFid, AUD_STR, Name,
4905                AUD_FID, OutFid, AUD_END);
4906     return code;
4907
4908 }                               /*SRXAFS_MakeDir */
4909
4910
4911 /*
4912  * This routine is called exclusively by SRXAFS_RemoveDir(), and should be
4913  * merged into it when possible.
4914  */
4915 static afs_int32
4916 SAFSS_RemoveDir(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4917                 struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4918 {
4919     Vnode *parentptr = 0;       /* vnode of input Directory */
4920     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4921     Vnode *targetptr = 0;       /* file to be deleted */
4922     AFSFid fileFid;             /* area for Fid from the directory */
4923     Error errorCode = 0;                /* error code */
4924     DirHandle dir;              /* Handle for dir package I/O */
4925     Volume *volptr = 0;         /* pointer to the volume header */
4926     struct client *client = 0;  /* pointer to client structure */
4927     afs_int32 rights, anyrights;        /* rights for this and any user */
4928     Vnode debugvnode1, debugvnode2;
4929     struct client *t_client;    /* tmp ptr to client data */
4930     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4931     struct rx_connection *tcon = rx_ConnectionOf(acall);
4932
4933     FidZero(&dir);
4934
4935     /* Get ptr to client data for user Id for logging */
4936     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4937     logHostAddr.s_addr = rxr_HostOf(tcon);
4938     ViceLog(1,
4939             ("SAFS_RemoveDir    %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4940              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4941              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4942     FS_LOCK;
4943     AFSCallStats.RemoveDir++, AFSCallStats.TotalCalls++;
4944     FS_UNLOCK;
4945     /*
4946      * Get the vnode and volume for the parent dir along with the caller's
4947      * rights to it
4948      */
4949     if ((errorCode =
4950          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4951                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4952                           &rights, &anyrights))) {
4953         goto Bad_RemoveDir;
4954     }
4955     debugvnode1 = *parentptr;
4956
4957     /* set volume synchronization information */
4958     SetVolumeSync(Sync, volptr);
4959
4960     /* Does the caller has delete (&write) access to the parent dir? */
4961     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
4962         goto Bad_RemoveDir;
4963     }
4964
4965     debugvnode2 = *parentptr;
4966     /* Do the actual delete of the desired (empty) directory, Name */
4967     if ((errorCode =
4968          DeleteTarget(parentptr, volptr, &targetptr, &dir, &fileFid, Name,
4969                       MustBeDIR))) {
4970         goto Bad_RemoveDir;
4971     }
4972
4973     /* Update the status for the parent dir; link count is also adjusted */
4974 #if FS_STATS_DETAILED
4975     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4976                              parentptr->disk.linkCount - 1,
4977                              client->InSameNetwork);
4978 #else
4979     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4980                              parentptr->disk.linkCount - 1);
4981 #endif /* FS_STATS_DETAILED */
4982
4983     /* Return to the caller the updated parent dir status */
4984     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4985
4986     /*
4987      * Note: it is not necessary to break the callback on fileFid, since
4988      * refcount is now 0, so no one should be able to refer to the dir
4989      * any longer
4990      */
4991     DeleteFileCallBacks(&fileFid);
4992
4993     /* convert the write lock to a read lock before breaking callbacks */
4994     VVnodeWriteToRead(&errorCode, parentptr);
4995     assert(!errorCode || errorCode == VSALVAGE);
4996
4997     /* break call back on DirFid and fileFid */
4998     BreakCallBack(client->host, DirFid, 0);
4999
5000   Bad_RemoveDir:
5001     /* Write the all modified vnodes (parent, new files) and volume back */
5002     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
5003                            volptr, &client);
5004     FidZap(&dir);
5005     ViceLog(2, ("SAFS_RemoveDir returns %d\n", errorCode));
5006     return errorCode;
5007
5008 }                               /*SAFSS_RemoveDir */
5009
5010
5011 afs_int32
5012 SRXAFS_RemoveDir(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
5013                  struct AFSFetchStatus * OutDirStatus,
5014                  struct AFSVolSync * Sync)
5015 {
5016     afs_int32 code;
5017     struct rx_connection *tcon;
5018     struct host *thost;
5019     struct client *t_client = NULL;     /* tmp ptr to client data */
5020 #if FS_STATS_DETAILED
5021     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5022     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5023     struct timeval elapsedTime; /* Transfer time */
5024
5025     /*
5026      * Set our stats pointer, remember when the RPC operation started, and
5027      * tally the operation.
5028      */
5029     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_REMOVEDIR]);
5030     FS_LOCK;
5031     (opP->numOps)++;
5032     FS_UNLOCK;
5033     FT_GetTimeOfDay(&opStartTime, 0);
5034 #endif /* FS_STATS_DETAILED */
5035
5036     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5037         goto Bad_RemoveDir;
5038
5039     code = SAFSS_RemoveDir(acall, DirFid, Name, OutDirStatus, Sync);
5040
5041   Bad_RemoveDir:
5042     code = CallPostamble(tcon, code, thost);
5043
5044     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5045
5046 #if FS_STATS_DETAILED
5047     FT_GetTimeOfDay(&opStopTime, 0);
5048     if (code == 0) {
5049         FS_LOCK;
5050         (opP->numSuccesses)++;
5051         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5052         fs_stats_AddTo((opP->sumTime), elapsedTime);
5053         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5054         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5055             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5056         }
5057         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5058             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5059         }
5060         FS_UNLOCK;
5061     }
5062 #endif /* FS_STATS_DETAILED */
5063
5064     osi_auditU(acall, RemoveDirEvent, code, 
5065                AUD_ID, t_client ? t_client->ViceId : 0,
5066                AUD_FID, DirFid, AUD_STR, Name, AUD_END);
5067     return code;
5068
5069 }                               /*SRXAFS_RemoveDir */
5070
5071
5072 /*
5073  * This routine is called exclusively by SRXAFS_SetLock(), and should be
5074  * merged into it when possible.
5075  */
5076 static afs_int32
5077 SAFSS_SetLock(struct rx_call *acall, struct AFSFid *Fid, ViceLockType type,
5078               struct AFSVolSync *Sync)
5079 {
5080     Vnode *targetptr = 0;       /* vnode of input file */
5081     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5082     Error errorCode = 0;                /* error code */
5083     Volume *volptr = 0;         /* pointer to the volume header */
5084     struct client *client = 0;  /* pointer to client structure */
5085     afs_int32 rights, anyrights;        /* rights for this and any user */
5086     struct client *t_client;    /* tmp ptr to client data */
5087     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5088     static char *locktype[4] = { "LockRead", "LockWrite", "LockExtend", "LockRelease" };
5089     struct rx_connection *tcon = rx_ConnectionOf(acall);
5090
5091     if (type != LockRead && type != LockWrite) {
5092         errorCode = EINVAL;
5093         goto Bad_SetLock;
5094     }
5095     /* Get ptr to client data for user Id for logging */
5096     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5097     logHostAddr.s_addr = rxr_HostOf(tcon);
5098     ViceLog(1,
5099             ("SAFS_SetLock type = %s Fid = %u.%u.%u, Host %s:%d, Id %d\n",
5100              locktype[(int)type], Fid->Volume, Fid->Vnode, Fid->Unique,
5101              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5102     FS_LOCK;
5103     AFSCallStats.SetLock++, AFSCallStats.TotalCalls++;
5104     FS_UNLOCK;
5105     /*
5106      * Get the vnode and volume for the desired file along with the caller's
5107      * rights to it
5108      */
5109     if ((errorCode =
5110          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5111                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5112                           &rights, &anyrights))) {
5113         goto Bad_SetLock;
5114     }
5115
5116     /* set volume synchronization information */
5117     SetVolumeSync(Sync, volptr);
5118
5119     /* Handle the particular type of set locking, type */
5120     errorCode = HandleLocking(targetptr, client, rights, type);
5121
5122   Bad_SetLock:
5123     /* Write the all modified vnodes (parent, new files) and volume back */
5124     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5125                            volptr, &client);
5126
5127     if ((errorCode == VREADONLY) && (type == LockRead))
5128         errorCode = 0;          /* allow read locks on RO volumes without saving state */
5129
5130     ViceLog(2, ("SAFS_SetLock returns %d\n", errorCode));
5131     return (errorCode);
5132
5133 }                               /*SAFSS_SetLock */
5134
5135
5136 afs_int32
5137 SRXAFS_OldSetLock(struct rx_call * acall, struct AFSFid * Fid,
5138                   ViceLockType type, struct AFSVolSync * Sync)
5139 {
5140     return SRXAFS_SetLock(acall, Fid, type, Sync);
5141 }                               /*SRXAFS_OldSetLock */
5142
5143
5144 afs_int32
5145 SRXAFS_SetLock(struct rx_call * acall, struct AFSFid * Fid, ViceLockType type,
5146                struct AFSVolSync * Sync)
5147 {
5148     afs_int32 code;
5149     struct rx_connection *tcon;
5150     struct host *thost;
5151     struct client *t_client = NULL;     /* tmp ptr to client data */
5152 #if FS_STATS_DETAILED
5153     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5154     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5155     struct timeval elapsedTime; /* Transfer time */
5156
5157     /*
5158      * Set our stats pointer, remember when the RPC operation started, and
5159      * tally the operation.
5160      */
5161     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SETLOCK]);
5162     FS_LOCK;
5163     (opP->numOps)++;
5164     FS_UNLOCK;
5165     FT_GetTimeOfDay(&opStartTime, 0);
5166 #endif /* FS_STATS_DETAILED */
5167
5168     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5169         goto Bad_SetLock;
5170
5171     code = SAFSS_SetLock(acall, Fid, type, Sync);
5172
5173   Bad_SetLock:
5174     code = CallPostamble(tcon, code, thost);
5175
5176     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5177
5178 #if FS_STATS_DETAILED
5179     FT_GetTimeOfDay(&opStopTime, 0);
5180     if (code == 0) {
5181         FS_LOCK;
5182         (opP->numSuccesses)++;
5183         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5184         fs_stats_AddTo((opP->sumTime), elapsedTime);
5185         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5186         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5187             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5188         }
5189         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5190             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5191         }
5192         FS_UNLOCK;
5193     }
5194 #endif /* FS_STATS_DETAILED */
5195
5196     osi_auditU(acall, SetLockEvent, code, 
5197                AUD_ID, t_client ? t_client->ViceId : 0, 
5198                AUD_FID, Fid, AUD_LONG, type, AUD_END);
5199     return code;
5200 }                               /*SRXAFS_SetLock */
5201
5202
5203 /*
5204  * This routine is called exclusively by SRXAFS_ExtendLock(), and should be
5205  * merged into it when possible.
5206  */
5207 static afs_int32
5208 SAFSS_ExtendLock(struct rx_call *acall, struct AFSFid *Fid,
5209                  struct AFSVolSync *Sync)
5210 {
5211     Vnode *targetptr = 0;       /* vnode of input file */
5212     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5213     Error errorCode = 0;                /* error code */
5214     Volume *volptr = 0;         /* pointer to the volume header */
5215     struct client *client = 0;  /* pointer to client structure */
5216     afs_int32 rights, anyrights;        /* rights for this and any user */
5217     struct client *t_client;    /* tmp ptr to client data */
5218     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5219     struct rx_connection *tcon = rx_ConnectionOf(acall);
5220
5221     /* Get ptr to client data for user Id for logging */
5222     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5223     logHostAddr.s_addr = rxr_HostOf(tcon);
5224     ViceLog(1,
5225             ("SAFS_ExtendLock Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
5226              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
5227              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5228     FS_LOCK;
5229     AFSCallStats.ExtendLock++, AFSCallStats.TotalCalls++;
5230     FS_UNLOCK;
5231     /*
5232      * Get the vnode and volume for the desired file along with the caller's
5233      * rights to it
5234      */
5235     if ((errorCode =
5236          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5237                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5238                           &rights, &anyrights))) {
5239         goto Bad_ExtendLock;
5240     }
5241
5242     /* set volume synchronization information */
5243     SetVolumeSync(Sync, volptr);
5244
5245     /* Handle the actual lock extension */
5246     errorCode = HandleLocking(targetptr, client, rights, LockExtend);
5247
5248   Bad_ExtendLock:
5249     /* Put back file's vnode and volume */
5250     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5251                            volptr, &client);
5252
5253     if ((errorCode == VREADONLY))       /* presumably, we already granted this lock */
5254         errorCode = 0;          /* under our generous policy re RO vols */
5255
5256     ViceLog(2, ("SAFS_ExtendLock returns %d\n", errorCode));
5257     return (errorCode);
5258
5259 }                               /*SAFSS_ExtendLock */
5260
5261
5262 afs_int32
5263 SRXAFS_OldExtendLock(struct rx_call * acall, struct AFSFid * Fid,
5264                      struct AFSVolSync * Sync)
5265 {
5266     return SRXAFS_ExtendLock(acall, Fid, Sync);
5267 }                               /*SRXAFS_OldExtendLock */
5268
5269
5270 afs_int32
5271 SRXAFS_ExtendLock(struct rx_call * acall, struct AFSFid * Fid,
5272                   struct AFSVolSync * Sync)
5273 {
5274     afs_int32 code;
5275     struct rx_connection *tcon;
5276     struct host *thost;
5277     struct client *t_client = NULL;     /* tmp ptr to client data */
5278 #if FS_STATS_DETAILED
5279     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5280     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5281     struct timeval elapsedTime; /* Transfer time */
5282
5283     /*
5284      * Set our stats pointer, remember when the RPC operation started, and
5285      * tally the operation.
5286      */
5287     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_EXTENDLOCK]);
5288     FS_LOCK;
5289     (opP->numOps)++;
5290     FS_UNLOCK;
5291     FT_GetTimeOfDay(&opStartTime, 0);
5292 #endif /* FS_STATS_DETAILED */
5293
5294     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5295         goto Bad_ExtendLock;
5296
5297     code = SAFSS_ExtendLock(acall, Fid, Sync);
5298
5299   Bad_ExtendLock:
5300     code = CallPostamble(tcon, code, thost);
5301
5302     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5303
5304 #if FS_STATS_DETAILED
5305     FT_GetTimeOfDay(&opStopTime, 0);
5306     if (code == 0) {
5307         FS_LOCK;
5308         (opP->numSuccesses)++;
5309         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5310         fs_stats_AddTo((opP->sumTime), elapsedTime);
5311         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5312         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5313             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5314         }
5315         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5316             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5317         }
5318         FS_UNLOCK;
5319     }
5320 #endif /* FS_STATS_DETAILED */
5321
5322     osi_auditU(acall, ExtendLockEvent, code, 
5323                AUD_ID, t_client ? t_client->ViceId : 0,
5324                AUD_FID, Fid, AUD_END);
5325     return code;
5326
5327 }                               /*SRXAFS_ExtendLock */
5328
5329
5330 /*
5331  * This routine is called exclusively by SRXAFS_ReleaseLock(), and should be
5332  * merged into it when possible.
5333  */
5334 static afs_int32
5335 SAFSS_ReleaseLock(struct rx_call *acall, struct AFSFid *Fid,
5336                   struct AFSVolSync *Sync)
5337 {
5338     Vnode *targetptr = 0;       /* vnode of input file */
5339     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5340     Error errorCode = 0;                /* error code */
5341     Volume *volptr = 0;         /* pointer to the volume header */
5342     struct client *client = 0;  /* pointer to client structure */
5343     afs_int32 rights, anyrights;        /* rights for this and any user */
5344     struct client *t_client;    /* tmp ptr to client data */
5345     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5346     struct rx_connection *tcon = rx_ConnectionOf(acall);
5347
5348     /* Get ptr to client data for user Id for logging */
5349     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5350     logHostAddr.s_addr = rxr_HostOf(tcon);
5351     ViceLog(1,
5352             ("SAFS_ReleaseLock Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
5353              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
5354              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5355     FS_LOCK;
5356     AFSCallStats.ReleaseLock++, AFSCallStats.TotalCalls++;
5357     FS_UNLOCK;
5358     /*
5359      * Get the vnode and volume for the desired file along with the caller's
5360      * rights to it
5361      */
5362     if ((errorCode =
5363          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5364                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5365                           &rights, &anyrights))) {
5366         goto Bad_ReleaseLock;
5367     }
5368
5369     /* set volume synchronization information */
5370     SetVolumeSync(Sync, volptr);
5371
5372     /* Handle the actual lock release */
5373     if ((errorCode = HandleLocking(targetptr, client, rights, LockRelease)))
5374         goto Bad_ReleaseLock;
5375
5376     /* if no more locks left, a callback would be triggered here */
5377     if (targetptr->disk.lock.lockCount <= 0) {
5378         /* convert the write lock to a read lock before breaking callbacks */
5379         VVnodeWriteToRead(&errorCode, targetptr);
5380         assert(!errorCode || errorCode == VSALVAGE);
5381         BreakCallBack(client->host, Fid, 0);
5382     }
5383
5384   Bad_ReleaseLock:
5385     /* Put back file's vnode and volume */
5386     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5387                            volptr, &client);
5388
5389     if ((errorCode == VREADONLY))       /* presumably, we already granted this lock */
5390         errorCode = 0;          /* under our generous policy re RO vols */
5391
5392     ViceLog(2, ("SAFS_ReleaseLock returns %d\n", errorCode));
5393     return (errorCode);
5394
5395 }                               /*SAFSS_ReleaseLock */
5396
5397
5398 afs_int32
5399 SRXAFS_OldReleaseLock(struct rx_call * acall, struct AFSFid * Fid,
5400                       struct AFSVolSync * Sync)
5401 {
5402     return SRXAFS_ReleaseLock(acall, Fid, Sync);
5403 }                               /*SRXAFS_OldReleaseLock */
5404
5405
5406 afs_int32
5407 SRXAFS_ReleaseLock(struct rx_call * acall, struct AFSFid * Fid,
5408                    struct AFSVolSync * Sync)
5409 {
5410     afs_int32 code;
5411     struct rx_connection *tcon;
5412     struct host *thost;
5413     struct client *t_client = NULL;     /* tmp ptr to client data */
5414 #if FS_STATS_DETAILED
5415     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5416     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5417     struct timeval elapsedTime; /* Transfer time */
5418
5419     /*
5420      * Set our stats pointer, remember when the RPC operation started, and
5421      * tally the operation.
5422      */
5423     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_RELEASELOCK]);
5424     FS_LOCK;
5425     (opP->numOps)++;
5426     FS_UNLOCK;
5427     FT_GetTimeOfDay(&opStartTime, 0);
5428 #endif /* FS_STATS_DETAILED */
5429
5430     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5431         goto Bad_ReleaseLock;
5432
5433     code = SAFSS_ReleaseLock(acall, Fid, Sync);
5434
5435   Bad_ReleaseLock:
5436     code = CallPostamble(tcon, code, thost);
5437
5438     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5439
5440 #if FS_STATS_DETAILED
5441     FT_GetTimeOfDay(&opStopTime, 0);
5442     if (code == 0) {
5443         FS_LOCK;
5444         (opP->numSuccesses)++;
5445         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5446         fs_stats_AddTo((opP->sumTime), elapsedTime);
5447         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5448         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5449             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5450         }
5451         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5452             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5453         }
5454         FS_UNLOCK;
5455     }
5456 #endif /* FS_STATS_DETAILED */
5457
5458     osi_auditU(acall, ReleaseLockEvent, code, 
5459                AUD_ID, t_client ? t_client->ViceId : 0, 
5460                AUD_FID, Fid, AUD_END);
5461     return code;
5462
5463 }                               /*SRXAFS_ReleaseLock */
5464
5465
5466 void
5467 SetSystemStats(struct AFSStatistics *stats)
5468 {
5469     /* Fix this sometime soon.. */
5470     /* Because hey, it's not like we have a network monitoring protocol... */
5471     struct timeval time;
5472
5473     /* this works on all system types */
5474     FT_GetTimeOfDay(&time, 0);
5475     stats->CurrentTime = time.tv_sec;
5476 }                               /*SetSystemStats */
5477
5478 void
5479 SetAFSStats(struct AFSStatistics *stats)
5480 {
5481     extern afs_int32 StartTime, CurrentConnections;
5482     int seconds;
5483
5484     FS_LOCK;
5485     stats->CurrentMsgNumber = 0;
5486     stats->OldestMsgNumber = 0;
5487     stats->StartTime = StartTime;
5488     stats->CurrentConnections = CurrentConnections;
5489     stats->TotalAFSCalls = AFSCallStats.TotalCalls;
5490     stats->TotalFetchs =
5491         AFSCallStats.FetchData + AFSCallStats.FetchACL +
5492         AFSCallStats.FetchStatus;
5493     stats->FetchDatas = AFSCallStats.FetchData;
5494     stats->FetchedBytes = AFSCallStats.TotalFetchedBytes;
5495     seconds = AFSCallStats.AccumFetchTime / 1000;
5496     if (seconds <= 0)
5497         seconds = 1;
5498     stats->FetchDataRate = AFSCallStats.TotalFetchedBytes / seconds;
5499     stats->TotalStores =
5500         AFSCallStats.StoreData + AFSCallStats.StoreACL +
5501         AFSCallStats.StoreStatus;
5502     stats->StoreDatas = AFSCallStats.StoreData;
5503     stats->StoredBytes = AFSCallStats.TotalStoredBytes;
5504     seconds = AFSCallStats.AccumStoreTime / 1000;
5505     if (seconds <= 0)
5506         seconds = 1;
5507     stats->StoreDataRate = AFSCallStats.TotalStoredBytes / seconds;
5508 #ifdef AFS_NT40_ENV
5509     stats->ProcessSize = -1;    /* TODO: */
5510 #else
5511     stats->ProcessSize = (afs_int32) ((long)sbrk(0) >> 10);
5512 #endif
5513     FS_UNLOCK;
5514     h_GetWorkStats((int *)&(stats->WorkStations),
5515                    (int *)&(stats->ActiveWorkStations), (int *)0,
5516                    (afs_int32) (FT_ApproxTime()) - (15 * 60));
5517
5518 }                               /*SetAFSStats */
5519
5520 /* Get disk related information from all AFS partitions. */
5521
5522 void
5523 SetVolumeStats(struct AFSStatistics *stats)
5524 {
5525     struct DiskPartition64 *part;
5526     int i = 0;
5527
5528     for (part = DiskPartitionList; part && i < AFS_MSTATDISKS;
5529          part = part->next) {
5530         stats->Disks[i].TotalBlocks = RoundInt64ToInt32(part->totalUsable);
5531         stats->Disks[i].BlocksAvailable = RoundInt64ToInt32(part->free);
5532         memset(stats->Disks[i].Name, 0, AFS_DISKNAMESIZE);
5533         strncpy(stats->Disks[i].Name, part->name, AFS_DISKNAMESIZE);
5534         i++;
5535     }
5536     while (i < AFS_MSTATDISKS) {
5537         stats->Disks[i].TotalBlocks = -1;
5538         i++;
5539     }
5540 }                               /*SetVolumeStats */
5541
5542 afs_int32
5543 SRXAFS_GetStatistics(struct rx_call *acall, struct ViceStatistics *Statistics)
5544 {
5545     afs_int32 code;
5546     struct rx_connection *tcon = rx_ConnectionOf(acall);
5547     struct host *thost;
5548     struct client *t_client = NULL;     /* tmp ptr to client data */
5549 #if FS_STATS_DETAILED
5550     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5551     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5552     struct timeval elapsedTime; /* Transfer time */
5553
5554     /*
5555      * Set our stats pointer, remember when the RPC operation started, and
5556      * tally the operation.
5557      */
5558     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETSTATISTICS]);
5559     FS_LOCK;
5560     (opP->numOps)++;
5561     FS_UNLOCK;
5562     FT_GetTimeOfDay(&opStartTime, 0);
5563 #endif /* FS_STATS_DETAILED */
5564
5565     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
5566         goto Bad_GetStatistics;
5567
5568     ViceLog(1, ("SAFS_GetStatistics Received\n"));
5569     FS_LOCK;
5570     AFSCallStats.GetStatistics++, AFSCallStats.TotalCalls++;
5571     FS_UNLOCK;
5572     memset(Statistics, 0, sizeof(*Statistics));
5573     SetAFSStats((struct AFSStatistics *)Statistics);
5574     SetVolumeStats((struct AFSStatistics *)Statistics);
5575     SetSystemStats((struct AFSStatistics *)Statistics);
5576
5577   Bad_GetStatistics:
5578     code = CallPostamble(tcon, code, thost);
5579
5580     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5581
5582 #if FS_STATS_DETAILED
5583     FT_GetTimeOfDay(&opStopTime, 0);
5584     if (code == 0) {
5585         FS_LOCK;
5586         (opP->numSuccesses)++;
5587         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5588         fs_stats_AddTo((opP->sumTime), elapsedTime);
5589         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5590         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5591             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5592         }
5593         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5594             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5595         }
5596         FS_UNLOCK;
5597     }
5598 #endif /* FS_STATS_DETAILED */
5599
5600     osi_auditU(acall, GetStatisticsEvent, code, 
5601                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5602     return code;
5603 }                               /*SRXAFS_GetStatistics */
5604
5605
5606 afs_int32
5607 SRXAFS_GetStatistics64(struct rx_call *acall, afs_int32 statsVersion, ViceStatistics64 *Statistics)
5608 {
5609     extern afs_int32 StartTime, CurrentConnections;
5610     int seconds;
5611     afs_int32 code;
5612     struct rx_connection *tcon = rx_ConnectionOf(acall);
5613     struct host *thost;
5614     struct client *t_client = NULL;     /* tmp ptr to client data */
5615     struct timeval time;
5616 #if FS_STATS_DETAILED
5617     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5618     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5619     struct timeval elapsedTime; /* Transfer time */
5620
5621     /*
5622      * Set our stats pointer, remember when the RPC operation started, and
5623      * tally the operation.
5624      */
5625     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETSTATISTICS]);
5626     FS_LOCK;
5627     (opP->numOps)++;
5628     FS_UNLOCK;
5629     FT_GetTimeOfDay(&opStartTime, 0);
5630 #endif /* FS_STATS_DETAILED */
5631
5632     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
5633         goto Bad_GetStatistics64;
5634
5635     ViceLog(1, ("SAFS_GetStatistics64 Received\n"));
5636     Statistics->ViceStatistics64_val = 
5637         malloc(statsVersion*sizeof(afs_int64));
5638     Statistics->ViceStatistics64_len = statsVersion;
5639     FS_LOCK;
5640     AFSCallStats.GetStatistics++, AFSCallStats.TotalCalls++;
5641     Statistics->ViceStatistics64_val[STATS64_STARTTIME] = StartTime;
5642     Statistics->ViceStatistics64_val[STATS64_CURRENTCONNECTIONS] =
5643         CurrentConnections;
5644     Statistics->ViceStatistics64_val[STATS64_TOTALVICECALLS] = 
5645         AFSCallStats.TotalCalls;
5646     Statistics->ViceStatistics64_val[STATS64_TOTALFETCHES] =
5647        AFSCallStats.FetchData + AFSCallStats.FetchACL +
5648        AFSCallStats.FetchStatus;
5649     Statistics->ViceStatistics64_val[STATS64_FETCHDATAS] = 
5650         AFSCallStats.FetchData;
5651     Statistics->ViceStatistics64_val[STATS64_FETCHEDBYTES] = 
5652         AFSCallStats.TotalFetchedBytes;
5653     seconds = AFSCallStats.AccumFetchTime / 1000;
5654     if (seconds <= 0)
5655         seconds = 1;
5656     Statistics->ViceStatistics64_val[STATS64_FETCHDATARATE] = 
5657         AFSCallStats.TotalFetchedBytes / seconds;
5658     Statistics->ViceStatistics64_val[STATS64_TOTALSTORES] =
5659         AFSCallStats.StoreData + AFSCallStats.StoreACL +
5660         AFSCallStats.StoreStatus;
5661     Statistics->ViceStatistics64_val[STATS64_STOREDATAS] = 
5662         AFSCallStats.StoreData;
5663     Statistics->ViceStatistics64_val[STATS64_STOREDBYTES] = 
5664         AFSCallStats.TotalStoredBytes;
5665     seconds = AFSCallStats.AccumStoreTime / 1000;
5666     if (seconds <= 0)
5667         seconds = 1;
5668     Statistics->ViceStatistics64_val[STATS64_STOREDATARATE] = 
5669         AFSCallStats.TotalStoredBytes / seconds;
5670 #ifdef AFS_NT40_ENV
5671     Statistics->ViceStatistics64_val[STATS64_PROCESSSIZE] = -1;
5672 #else
5673     Statistics->ViceStatistics64_val[STATS64_PROCESSSIZE] = 
5674         (afs_int32) ((long)sbrk(0) >> 10);
5675 #endif
5676     FS_UNLOCK;
5677     h_GetWorkStats((int *)&(Statistics->ViceStatistics64_val[STATS64_WORKSTATIONS]),
5678                    (int *)&(Statistics->ViceStatistics64_val[STATS64_ACTIVEWORKSTATIONS]), 
5679                    (int *)0,
5680                    (afs_int32) (FT_ApproxTime()) - (15 * 60));
5681
5682
5683
5684     /* this works on all system types */
5685     FT_GetTimeOfDay(&time, 0);
5686     Statistics->ViceStatistics64_val[STATS64_CURRENTTIME] = time.tv_sec;
5687
5688   Bad_GetStatistics64:
5689     code = CallPostamble(tcon, code, thost);
5690
5691     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5692
5693 #if FS_STATS_DETAILED
5694     FT_GetTimeOfDay(&opStopTime, 0);
5695     if (code == 0) {
5696         FS_LOCK;
5697         (opP->numSuccesses)++;
5698         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5699         fs_stats_AddTo((opP->sumTime), elapsedTime);
5700         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5701         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5702             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5703         }
5704         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5705             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5706         }
5707         FS_UNLOCK;
5708     }
5709 #endif /* FS_STATS_DETAILED */
5710
5711     osi_auditU(acall, GetStatisticsEvent, code, 
5712                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5713     return code;
5714 }                               /*SRXAFS_GetStatistics */
5715
5716
5717 /*------------------------------------------------------------------------
5718  * EXPORTED SRXAFS_XStatsVersion
5719  *
5720  * Description:
5721  *      Routine called by the server-side RPC interface to implement
5722  *      pulling out the xstat version number for the File Server.
5723  *
5724  * Arguments:
5725  *      a_versionP : Ptr to the version number variable to set.
5726  *
5727  * Returns:
5728  *      0 (always)
5729  *
5730  * Environment:
5731  *      Nothing interesting.
5732  *
5733  * Side Effects:
5734  *      As advertised.
5735  *------------------------------------------------------------------------*/
5736
5737 afs_int32
5738 SRXAFS_XStatsVersion(struct rx_call * a_call, afs_int32 * a_versionP)
5739 {                               /*SRXAFS_XStatsVersion */
5740
5741     struct client *t_client = NULL;     /* tmp ptr to client data */
5742     struct rx_connection *tcon = rx_ConnectionOf(a_call);
5743 #if FS_STATS_DETAILED
5744     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5745     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5746     struct timeval elapsedTime; /* Transfer time */
5747
5748     /*
5749      * Set our stats pointer, remember when the RPC operation started, and
5750      * tally the operation.
5751      */
5752     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_XSTATSVERSION]);
5753     FS_LOCK;
5754     (opP->numOps)++;
5755     FS_UNLOCK;
5756     FT_GetTimeOfDay(&opStartTime, 0);
5757 #endif /* FS_STATS_DETAILED */
5758
5759     *a_versionP = AFS_XSTAT_VERSION;
5760
5761     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5762
5763 #if FS_STATS_DETAILED
5764     FT_GetTimeOfDay(&opStopTime, 0);
5765     fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5766     fs_stats_AddTo((opP->sumTime), elapsedTime);
5767     fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5768     if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5769         fs_stats_TimeAssign((opP->minTime), elapsedTime);
5770     }
5771     if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5772         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5773     }
5774     FS_LOCK;
5775     (opP->numSuccesses)++;
5776     FS_UNLOCK;
5777 #endif /* FS_STATS_DETAILED */
5778
5779     osi_auditU(a_call, XStatsVersionEvent, 0, 
5780                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5781     return (0);
5782 }                               /*SRXAFS_XStatsVersion */
5783
5784
5785 /*------------------------------------------------------------------------
5786  * PRIVATE FillPerfValues
5787  *
5788  * Description:
5789  *      Routine called to fill a regular performance data structure.
5790  *
5791  * Arguments:
5792  *      a_perfP : Ptr to perf structure to fill
5793  *
5794  * Returns:
5795  *      Nothing.
5796  *
5797  * Environment:
5798  *      Various collections need this info, so the guts were put in
5799  *      this separate routine.
5800  *
5801  * Side Effects:
5802  *      As advertised.
5803  *------------------------------------------------------------------------*/
5804
5805 static void
5806 FillPerfValues(struct afs_PerfStats *a_perfP)
5807 {                               /*FillPerfValues */
5808     afs_uint32 hi, lo;
5809     int dir_Buffers;            /*# buffers in use by dir package */
5810     int dir_Calls;              /*# read calls in dir package */
5811     int dir_IOs;                /*# I/O ops in dir package */
5812
5813     /*
5814      * Vnode cache section.
5815      */
5816     a_perfP->vcache_L_Entries = VnodeClassInfo[vLarge].cacheSize;
5817     a_perfP->vcache_L_Allocs = VnodeClassInfo[vLarge].allocs;
5818     a_perfP->vcache_L_Gets = VnodeClassInfo[vLarge].gets;
5819     a_perfP->vcache_L_Reads = VnodeClassInfo[vLarge].reads;
5820     a_perfP->vcache_L_Writes = VnodeClassInfo[vLarge].writes;
5821     a_perfP->vcache_S_Entries = VnodeClassInfo[vSmall].cacheSize;
5822     a_perfP->vcache_S_Allocs = VnodeClassInfo[vSmall].allocs;
5823     a_perfP->vcache_S_Gets = VnodeClassInfo[vSmall].gets;
5824     a_perfP->vcache_S_Reads = VnodeClassInfo[vSmall].reads;
5825     a_perfP->vcache_S_Writes = VnodeClassInfo[vSmall].writes;
5826     a_perfP->vcache_H_Entries = VStats.hdr_cache_size;
5827     SplitInt64(VStats.hdr_gets, hi, lo);
5828     a_perfP->vcache_H_Gets = lo;
5829     SplitInt64(VStats.hdr_loads, hi, lo);
5830     a_perfP->vcache_H_Replacements = lo;
5831
5832     /*
5833      * Directory section.
5834      */
5835     DStat(&dir_Buffers, &dir_Calls, &dir_IOs);
5836     a_perfP->dir_Buffers = (afs_int32) dir_Buffers;
5837     a_perfP->dir_Calls = (afs_int32) dir_Calls;
5838     a_perfP->dir_IOs = (afs_int32) dir_IOs;
5839
5840     /*
5841      * Rx section.
5842      */
5843     a_perfP->rx_packetRequests = (afs_int32) rx_stats.packetRequests;
5844     a_perfP->rx_noPackets_RcvClass =
5845         (afs_int32) rx_stats.receivePktAllocFailures;
5846     a_perfP->rx_noPackets_SendClass =
5847         (afs_int32) rx_stats.sendPktAllocFailures;
5848     a_perfP->rx_noPackets_SpecialClass =
5849         (afs_int32) rx_stats.specialPktAllocFailures;
5850     a_perfP->rx_socketGreedy = (afs_int32) rx_stats.socketGreedy;
5851     a_perfP->rx_bogusPacketOnRead = (afs_int32) rx_stats.bogusPacketOnRead;
5852     a_perfP->rx_bogusHost = (afs_int32) rx_stats.bogusHost;
5853     a_perfP->rx_noPacketOnRead = (afs_int32) rx_stats.noPacketOnRead;
5854     a_perfP->rx_noPacketBuffersOnRead =
5855         (afs_int32) rx_stats.noPacketBuffersOnRead;
5856     a_perfP->rx_selects = (afs_int32) rx_stats.selects;
5857     a_perfP->rx_sendSelects = (afs_int32) rx_stats.sendSelects;
5858     a_perfP->rx_packetsRead_RcvClass =
5859         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_RECEIVE];
5860     a_perfP->rx_packetsRead_SendClass =
5861         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_SEND];
5862     a_perfP->rx_packetsRead_SpecialClass =
5863         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_SPECIAL];
5864     a_perfP->rx_dataPacketsRead = (afs_int32) rx_stats.dataPacketsRead;
5865     a_perfP->rx_ackPacketsRead = (afs_int32) rx_stats.ackPacketsRead;
5866     a_perfP->rx_dupPacketsRead = (afs_int32) rx_stats.dupPacketsRead;
5867     a_perfP->rx_spuriousPacketsRead =
5868         (afs_int32) rx_stats.spuriousPacketsRead;
5869     a_perfP->rx_packetsSent_RcvClass =
5870         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_RECEIVE];
5871     a_perfP->rx_packetsSent_SendClass =
5872         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_SEND];
5873     a_perfP->rx_packetsSent_SpecialClass =
5874         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_SPECIAL];
5875     a_perfP->rx_ackPacketsSent = (afs_int32) rx_stats.ackPacketsSent;
5876     a_perfP->rx_pingPacketsSent = (afs_int32) rx_stats.pingPacketsSent;
5877     a_perfP->rx_abortPacketsSent = (afs_int32) rx_stats.abortPacketsSent;
5878     a_perfP->rx_busyPacketsSent = (afs_int32) rx_stats.busyPacketsSent;
5879     a_perfP->rx_dataPacketsSent = (afs_int32) rx_stats.dataPacketsSent;
5880     a_perfP->rx_dataPacketsReSent = (afs_int32) rx_stats.dataPacketsReSent;
5881     a_perfP->rx_dataPacketsPushed = (afs_int32) rx_stats.dataPacketsPushed;
5882     a_perfP->rx_ignoreAckedPacket = (afs_int32) rx_stats.ignoreAckedPacket;
5883     a_perfP->rx_totalRtt_Sec = (afs_int32) rx_stats.totalRtt.sec;
5884     a_perfP->rx_totalRtt_Usec = (afs_int32) rx_stats.totalRtt.usec;
5885     a_perfP->rx_minRtt_Sec = (afs_int32) rx_stats.minRtt.sec;
5886     a_perfP->rx_minRtt_Usec = (afs_int32) rx_stats.minRtt.usec;
5887     a_perfP->rx_maxRtt_Sec = (afs_int32) rx_stats.maxRtt.sec;
5888     a_perfP->rx_maxRtt_Usec = (afs_int32) rx_stats.maxRtt.usec;
5889     a_perfP->rx_nRttSamples = (afs_int32) rx_stats.nRttSamples;
5890     a_perfP->rx_nServerConns = (afs_int32) rx_stats.nServerConns;
5891     a_perfP->rx_nClientConns = (afs_int32) rx_stats.nClientConns;
5892     a_perfP->rx_nPeerStructs = (afs_int32) rx_stats.nPeerStructs;
5893     a_perfP->rx_nCallStructs = (afs_int32) rx_stats.nCallStructs;
5894     a_perfP->rx_nFreeCallStructs = (afs_int32) rx_stats.nFreeCallStructs;
5895
5896     a_perfP->host_NumHostEntries = HTs;
5897     a_perfP->host_HostBlocks = HTBlocks;
5898     h_GetHostNetStats(&(a_perfP->host_NonDeletedHosts),
5899                       &(a_perfP->host_HostsInSameNetOrSubnet),
5900                       &(a_perfP->host_HostsInDiffSubnet),
5901                       &(a_perfP->host_HostsInDiffNetwork));
5902     a_perfP->host_NumClients = CEs;
5903     a_perfP->host_ClientBlocks = CEBlocks;
5904
5905     a_perfP->sysname_ID = afs_perfstats.sysname_ID;
5906     a_perfP->rx_nBusies = (afs_int32) rx_stats.nBusies;
5907     a_perfP->fs_nBusies = afs_perfstats.fs_nBusies;
5908 }                               /*FillPerfValues */
5909
5910
5911 /*------------------------------------------------------------------------
5912  * EXPORTED SRXAFS_GetXStats
5913  *
5914  * Description:
5915  *      Routine called by the server-side callback RPC interface to
5916  *      implement getting the given data collection from the extended
5917  *      File Server statistics.
5918  *
5919  * Arguments:
5920  *      a_call              : Ptr to Rx call on which this request came in.
5921  *      a_clientVersionNum  : Client version number.
5922  *      a_opCode            : Desired operation.
5923  *      a_serverVersionNumP : Ptr to version number to set.
5924  *      a_timeP             : Ptr to time value (seconds) to set.
5925  *      a_dataP             : Ptr to variable array structure to return
5926  *                            stuff in.
5927  *
5928  * Returns:
5929  *      0 (always).
5930  *
5931  * Environment:
5932  *      Nothing interesting.
5933  *
5934  * Side Effects:
5935  *      As advertised.
5936  *------------------------------------------------------------------------*/
5937
5938 afs_int32
5939 SRXAFS_GetXStats(struct rx_call *a_call, afs_int32 a_clientVersionNum,
5940                  afs_int32 a_collectionNumber, afs_int32 * a_srvVersionNumP,
5941                  afs_int32 * a_timeP, AFS_CollData * a_dataP)
5942 {                               /*SRXAFS_GetXStats */
5943
5944     register int code;          /*Return value */
5945     afs_int32 *dataBuffP;       /*Ptr to data to be returned */
5946     afs_int32 dataBytes;        /*Bytes in data buffer */
5947 #if FS_STATS_DETAILED
5948     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5949     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5950     struct timeval elapsedTime; /* Transfer time */
5951
5952     /*
5953      * Set our stats pointer, remember when the RPC operation started, and
5954      * tally the operation.
5955      */
5956     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETXSTATS]);
5957     FS_LOCK;
5958     (opP->numOps)++;
5959     FS_UNLOCK;
5960     FT_GetTimeOfDay(&opStartTime, 0);
5961 #endif /* FS_STATS_DETAILED */
5962
5963     /*
5964      * Record the time of day and the server version number.
5965      */
5966     *a_srvVersionNumP = AFS_XSTAT_VERSION;
5967     *a_timeP = FT_ApproxTime();
5968
5969     /*
5970      * Stuff the appropriate data in there (assume victory)
5971      */
5972     code = 0;
5973
5974     ViceLog(1,
5975             ("Received GetXStats call for collection %d\n",
5976              a_collectionNumber));
5977
5978 #if 0
5979     /*
5980      * We're not keeping stats, so just return successfully with
5981      * no data.
5982      */
5983     a_dataP->AFS_CollData_len = 0;
5984     a_dataP->AFS_CollData_val = NULL;
5985 #endif /* 0 */
5986
5987     switch (a_collectionNumber) {
5988     case AFS_XSTATSCOLL_CALL_INFO:
5989         /*
5990          * Pass back all the call-count-related data.
5991          *
5992          * >>> We are forced to allocate a separate area in which to
5993          * >>> put this stuff in by the RPC stub generator, since it
5994          * >>> will be freed at the tail end of the server stub code.
5995          */
5996 #if 0
5997         /*
5998          * I don't think call-level stats are being collected yet
5999          * for the File Server.
6000          */
6001         dataBytes = sizeof(struct afs_Stats);
6002         dataBuffP = (afs_int32 *) malloc(dataBytes);
6003         memcpy(dataBuffP, &afs_cmstats, dataBytes);
6004         a_dataP->AFS_CollData_len = dataBytes >> 2;
6005         a_dataP->AFS_CollData_val = dataBuffP;
6006 #else
6007         a_dataP->AFS_CollData_len = 0;
6008         a_dataP->AFS_CollData_val = NULL;
6009 #endif /* 0 */
6010         break;
6011
6012     case AFS_XSTATSCOLL_PERF_INFO:
6013         /*
6014          * Pass back all the regular performance-related data.
6015          *
6016          * >>> We are forced to allocate a separate area in which to
6017          * >>> put this stuff in by the RPC stub generator, since it
6018          * >>> will be freed at the tail end of the server stub code.
6019          */
6020
6021         afs_perfstats.numPerfCalls++;
6022         FillPerfValues(&afs_perfstats);
6023
6024         /*
6025          * Don't overwrite the spares at the end.
6026          */
6027
6028         dataBytes = sizeof(struct afs_PerfStats);
6029         dataBuffP = (afs_int32 *) malloc(dataBytes);
6030         memcpy(dataBuffP, &afs_perfstats, dataBytes);
6031         a_dataP->AFS_CollData_len = dataBytes >> 2;
6032         a_dataP->AFS_CollData_val = dataBuffP;
6033         break;
6034
6035     case AFS_XSTATSCOLL_FULL_PERF_INFO:
6036         /*
6037          * Pass back the full collection of performance-related data.
6038          * We have to stuff the basic, overall numbers in, but the
6039          * detailed numbers are kept in the structure already.
6040          *
6041          * >>> We are forced to allocate a separate area in which to
6042          * >>> put this stuff in by the RPC stub generator, since it
6043          * >>> will be freed at the tail end of the server stub code.
6044          */
6045
6046         afs_perfstats.numPerfCalls++;
6047 #if FS_STATS_DETAILED
6048         afs_FullPerfStats.overall.numPerfCalls = afs_perfstats.numPerfCalls;
6049         FillPerfValues(&afs_FullPerfStats.overall);
6050
6051         /*
6052          * Don't overwrite the spares at the end.
6053          */
6054
6055         dataBytes = sizeof(struct fs_stats_FullPerfStats);
6056         dataBuffP = (afs_int32 *) malloc(dataBytes);
6057         memcpy(dataBuffP, &afs_FullPerfStats, dataBytes);
6058         a_dataP->AFS_CollData_len = dataBytes >> 2;
6059         a_dataP->AFS_CollData_val = dataBuffP;
6060 #endif
6061         break;
6062
6063     case AFS_XSTATSCOLL_CBSTATS:
6064         afs_perfstats.numPerfCalls++;
6065
6066         dataBytes = sizeof(struct cbcounters);
6067         dataBuffP = (afs_int32 *) malloc(dataBytes);
6068         {
6069             extern struct cbcounters cbstuff;
6070             dataBuffP[0]=cbstuff.DeleteFiles;
6071             dataBuffP[1]=cbstuff.DeleteCallBacks;
6072             dataBuffP[2]=cbstuff.BreakCallBacks;
6073             dataBuffP[3]=cbstuff.AddCallBacks;
6074             dataBuffP[4]=cbstuff.GotSomeSpaces;
6075             dataBuffP[5]=cbstuff.DeleteAllCallBacks;
6076             dataBuffP[6]=cbstuff.nFEs;
6077             dataBuffP[7]=cbstuff.nCBs;
6078             dataBuffP[8]=cbstuff.nblks;
6079             dataBuffP[9]=cbstuff.CBsTimedOut;
6080             dataBuffP[10]=cbstuff.nbreakers;
6081             dataBuffP[11]=cbstuff.GSS1;
6082             dataBuffP[12]=cbstuff.GSS2;
6083             dataBuffP[13]=cbstuff.GSS3;
6084             dataBuffP[14]=cbstuff.GSS4;
6085             dataBuffP[15]=cbstuff.GSS5;
6086         }
6087
6088         a_dataP->AFS_CollData_len = dataBytes >> 2;
6089         a_dataP->AFS_CollData_val = dataBuffP;
6090         break;
6091
6092
6093     default:
6094         /*
6095          * Illegal collection number.
6096          */
6097         a_dataP->AFS_CollData_len = 0;
6098         a_dataP->AFS_CollData_val = NULL;
6099         code = 1;
6100     }                           /*Switch on collection number */
6101
6102 #if FS_STATS_DETAILED
6103     FT_GetTimeOfDay(&opStopTime, 0);
6104     if (code == 0) {
6105         FS_LOCK;
6106         (opP->numSuccesses)++;
6107         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6108         fs_stats_AddTo((opP->sumTime), elapsedTime);
6109         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6110         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6111             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6112         }
6113         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6114             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6115         }
6116         FS_UNLOCK;
6117     }
6118 #endif /* FS_STATS_DETAILED */
6119
6120     return (code);
6121
6122 }                               /*SRXAFS_GetXStats */
6123
6124
6125 static afs_int32
6126 common_GiveUpCallBacks(struct rx_call *acall, struct AFSCBFids *FidArray,
6127                        struct AFSCBs *CallBackArray)
6128 {
6129     afs_int32 errorCode = 0;
6130     register int i;
6131     struct client *client = 0;
6132     struct rx_connection *tcon;
6133     struct host *thost;
6134 #if FS_STATS_DETAILED
6135     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6136     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6137     struct timeval elapsedTime; /* Transfer time */
6138
6139     /*
6140      * Set our stats pointer, remember when the RPC operation started, and
6141      * tally the operation.
6142      */
6143     opP =
6144         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GIVEUPCALLBACKS]);
6145     FS_LOCK;
6146     (opP->numOps)++;
6147     FS_UNLOCK;
6148     FT_GetTimeOfDay(&opStartTime, 0);
6149 #endif /* FS_STATS_DETAILED */
6150
6151     if (FidArray)
6152         ViceLog(1,
6153                 ("SAFS_GiveUpCallBacks (Noffids=%d)\n",
6154                  FidArray->AFSCBFids_len));
6155
6156     FS_LOCK;
6157     AFSCallStats.GiveUpCallBacks++, AFSCallStats.TotalCalls++;
6158     FS_UNLOCK;
6159     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6160         goto Bad_GiveUpCallBacks;
6161
6162     if (!FidArray && !CallBackArray) {
6163         ViceLog(1,
6164                 ("SAFS_GiveUpAllCallBacks: host=%x\n",
6165                  (tcon->peer ? tcon->peer->host : 0)));
6166         errorCode = GetClient(tcon, &client);
6167         if (!errorCode) {
6168             H_LOCK;
6169             DeleteAllCallBacks_r(client->host, 1);
6170             H_UNLOCK;
6171             PutClient(&client);
6172         }
6173     } else {
6174         if (FidArray->AFSCBFids_len < CallBackArray->AFSCBs_len) {
6175             ViceLog(0,
6176                     ("GiveUpCallBacks: #Fids %d < #CallBacks %d, host=%x\n",
6177                      FidArray->AFSCBFids_len, CallBackArray->AFSCBs_len,
6178                      (tcon->peer ? tcon->peer->host : 0)));
6179             errorCode = EINVAL;
6180             goto Bad_GiveUpCallBacks;
6181         }
6182
6183         errorCode = GetClient(tcon, &client);
6184         if (!errorCode) {
6185             for (i = 0; i < FidArray->AFSCBFids_len; i++) {
6186                 register struct AFSFid *fid = &(FidArray->AFSCBFids_val[i]);
6187                 DeleteCallBack(client->host, fid);
6188             }
6189             PutClient(&client);
6190         }
6191     }
6192
6193   Bad_GiveUpCallBacks:
6194     errorCode = CallPostamble(tcon, errorCode, thost);
6195
6196 #if FS_STATS_DETAILED
6197     FT_GetTimeOfDay(&opStopTime, 0);
6198     if (errorCode == 0) {
6199         FS_LOCK;
6200         (opP->numSuccesses)++;
6201         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6202         fs_stats_AddTo((opP->sumTime), elapsedTime);
6203         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6204         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6205             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6206         }
6207         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6208             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6209         }
6210         FS_UNLOCK;
6211     }
6212 #endif /* FS_STATS_DETAILED */
6213     return errorCode;
6214
6215 }                               /*common_GiveUpCallBacks */
6216
6217
6218 afs_int32
6219 SRXAFS_GiveUpCallBacks(struct rx_call * acall, struct AFSCBFids * FidArray,
6220                        struct AFSCBs * CallBackArray)
6221 {
6222     return common_GiveUpCallBacks(acall, FidArray, CallBackArray);
6223 }                               /*SRXAFS_GiveUpCallBacks */
6224
6225 afs_int32
6226 SRXAFS_GiveUpAllCallBacks(struct rx_call * acall)
6227 {
6228     return common_GiveUpCallBacks(acall, 0, 0);
6229 }                               /*SRXAFS_GiveUpAllCallBacks */
6230
6231
6232 afs_int32
6233 SRXAFS_NGetVolumeInfo(struct rx_call * acall, char *avolid,
6234                       struct AFSVolumeInfo * avolinfo)
6235 {
6236     return (VNOVOL);            /* XXX Obsolete routine XXX */
6237
6238 }                               /*SRXAFS_NGetVolumeInfo */
6239
6240
6241 /*
6242  * Dummy routine. Should never be called (the cache manager should only 
6243  * invoke this interface when communicating with a AFS/DFS Protocol
6244  * Translator).
6245  */
6246 afs_int32
6247 SRXAFS_Lookup(struct rx_call * call_p, struct AFSFid * afs_dfid_p,
6248               char *afs_name_p, struct AFSFid * afs_fid_p,
6249               struct AFSFetchStatus * afs_status_p,
6250               struct AFSFetchStatus * afs_dir_status_p,
6251               struct AFSCallBack * afs_callback_p,
6252               struct AFSVolSync * afs_sync_p)
6253 {
6254     return EINVAL;
6255 }
6256
6257
6258 afs_int32
6259 SRXAFS_GetCapabilities(struct rx_call * acall, Capabilities * capabilities)
6260 {
6261     afs_int32 code;
6262     struct rx_connection *tcon;
6263     struct host *thost;
6264     afs_uint32 *dataBuffP;
6265     afs_int32 dataBytes;
6266
6267     FS_LOCK;
6268     AFSCallStats.GetCapabilities++, AFSCallStats.TotalCalls++;
6269     afs_FullPerfStats.overall.fs_nGetCaps++;
6270     FS_UNLOCK;
6271     ViceLog(2, ("SAFS_GetCapabilties\n"));
6272
6273     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
6274         goto Bad_GetCaps;
6275
6276     dataBytes = 1 * sizeof(afs_int32);
6277     dataBuffP = (afs_uint32 *) malloc(dataBytes);
6278     dataBuffP[0] = VICED_CAPABILITY_ERRORTRANS | VICED_CAPABILITY_WRITELOCKACL;
6279 #if defined(AFS_64BIT_ENV)
6280     dataBuffP[0] |= VICED_CAPABILITY_64BITFILES;
6281 #endif
6282     if (saneacls)
6283         dataBuffP[0] |= VICED_CAPABILITY_SANEACLS;
6284
6285     capabilities->Capabilities_len = dataBytes / sizeof(afs_int32);
6286     capabilities->Capabilities_val = dataBuffP;
6287
6288   Bad_GetCaps:
6289     code = CallPostamble(tcon, code, thost);
6290
6291
6292     return 0;
6293 }
6294
6295 afs_int32
6296 SRXAFS_FlushCPS(struct rx_call * acall, struct ViceIds * vids,
6297                 struct IPAddrs * addrs, afs_int32 spare1, afs_int32 * spare2,
6298                 afs_int32 * spare3)
6299 {
6300     int i;
6301     afs_int32 nids, naddrs;
6302     afs_int32 *vd, *addr;
6303     Error errorCode = 0;                /* return code to caller */
6304     struct client *client = 0;
6305
6306     ViceLog(1, ("SRXAFS_FlushCPS\n"));
6307     FS_LOCK;
6308     AFSCallStats.TotalCalls++;
6309     FS_UNLOCK;
6310     nids = vids->ViceIds_len;   /* # of users in here */
6311     naddrs = addrs->IPAddrs_len;        /* # of hosts in here */
6312     if (nids < 0 || naddrs < 0) {
6313         errorCode = EINVAL;
6314         goto Bad_FlushCPS;
6315     }
6316
6317     vd = vids->ViceIds_val;
6318     for (i = 0; i < nids; i++, vd++) {
6319         if (!*vd)
6320             continue;
6321         client = h_ID2Client(*vd);      /* returns write locked and refCounted, or NULL */
6322         if (!client)
6323             continue;
6324
6325         client->prfail = 2;     /* Means re-eval client's cps */
6326 #ifdef  notdef
6327         if (client->tcon) {
6328             rx_SetRock(((struct rx_connection *)client->tcon), 0);
6329         }
6330 #endif
6331         if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val) {
6332             free(client->CPS.prlist_val);
6333             client->CPS.prlist_val = NULL;
6334             client->CPS.prlist_len = 0;
6335         }
6336         ReleaseWriteLock(&client->lock);
6337         PutClient(&client);
6338     }
6339
6340     addr = addrs->IPAddrs_val;
6341     for (i = 0; i < naddrs; i++, addr++) {
6342         if (*addr)
6343             h_flushhostcps(*addr, htons(7001));
6344     }
6345
6346   Bad_FlushCPS:
6347     ViceLog(2, ("SAFS_FlushCPS  returns %d\n", errorCode));
6348     return errorCode;
6349 }                               /*SRXAFS_FlushCPS */
6350
6351 /* worthless hack to let CS keep running ancient software */
6352 static int
6353 afs_vtoi(register char *aname)
6354 {
6355     register afs_int32 temp;
6356     register int tc;
6357
6358     temp = 0;
6359     while ((tc = *aname++)) {
6360         if (tc > '9' || tc < '0')
6361             return 0;           /* invalid name */
6362         temp *= 10;
6363         temp += tc - '0';
6364     }
6365     return temp;
6366 }
6367
6368 /*
6369  * may get name or #, but must handle all weird cases (recognize readonly
6370  * or backup volumes by name or #
6371  */
6372 static afs_int32
6373 CopyVolumeEntry(char *aname, register struct vldbentry *ave,
6374                 register struct VolumeInfo *av)
6375 {
6376     register int i, j, vol;
6377     afs_int32 mask, whichType;
6378     afs_uint32 *serverHost, *typePtr;
6379
6380     /* figure out what type we want if by name */
6381     i = strlen(aname);
6382     if (i >= 8 && strcmp(aname + i - 7, ".backup") == 0)
6383         whichType = BACKVOL;
6384     else if (i >= 10 && strcmp(aname + i - 9, ".readonly") == 0)
6385         whichType = ROVOL;
6386     else
6387         whichType = RWVOL;
6388
6389     vol = afs_vtoi(aname);
6390     if (vol == 0)
6391         vol = ave->volumeId[whichType];
6392
6393     /*
6394      * Now vol has volume # we're interested in.  Next, figure out the type
6395      * of the volume by looking finding it in the vldb entry
6396      */
6397     if ((ave->flags & VLF_RWEXISTS) && vol == ave->volumeId[RWVOL]) {
6398         mask = VLSF_RWVOL;
6399         whichType = RWVOL;
6400     } else if ((ave->flags & VLF_ROEXISTS) && vol == ave->volumeId[ROVOL]) {
6401         mask = VLSF_ROVOL;
6402         whichType = ROVOL;
6403     } else if ((ave->flags & VLF_BACKEXISTS) && vol == ave->volumeId[BACKVOL]) {
6404         mask = VLSF_RWVOL;      /* backup always is on the same volume as parent */
6405         whichType = BACKVOL;
6406     } else
6407         return EINVAL;          /* error: can't find volume in vldb entry */
6408
6409     typePtr = &av->Type0;
6410     serverHost = &av->Server0;
6411     av->Vid = vol;
6412     av->Type = whichType;
6413     av->Type0 = av->Type1 = av->Type2 = av->Type3 = av->Type4 = 0;
6414     if (ave->flags & VLF_RWEXISTS)
6415         typePtr[RWVOL] = ave->volumeId[RWVOL];
6416     if (ave->flags & VLF_ROEXISTS)
6417         typePtr[ROVOL] = ave->volumeId[ROVOL];
6418     if (ave->flags & VLF_BACKEXISTS)
6419         typePtr[BACKVOL] = ave->volumeId[BACKVOL];
6420
6421     for (i = 0, j = 0; i < ave->nServers; i++) {
6422         if ((ave->serverFlags[i] & mask) == 0)
6423             continue;           /* wrong volume */
6424         serverHost[j] = ave->serverNumber[i];
6425         j++;
6426     }
6427     av->ServerCount = j;
6428     if (j < 8)
6429         serverHost[j++] = 0;    /* bogus 8, but compat only now */
6430     return 0;
6431 }
6432
6433 static afs_int32
6434 TryLocalVLServer(char *avolid, struct VolumeInfo *avolinfo)
6435 {
6436     static struct rx_connection *vlConn = 0;
6437     static int down = 0;
6438     static afs_int32 lastDownTime = 0;
6439     struct vldbentry tve;
6440     struct rx_securityClass *vlSec;
6441     register afs_int32 code;
6442
6443     if (!vlConn) {
6444         vlSec = rxnull_NewClientSecurityObject();
6445         vlConn =
6446             rx_NewConnection(htonl(0x7f000001), htons(7003), 52, vlSec, 0);
6447         rx_SetConnDeadTime(vlConn, 15); /* don't wait long */
6448     }
6449     if (down && (FT_ApproxTime() < lastDownTime + 180)) {
6450         return 1;               /* failure */
6451     }
6452
6453     code = VL_GetEntryByNameO(vlConn, avolid, &tve);
6454     if (code >= 0)
6455         down = 0;               /* call worked */
6456     if (code) {
6457         if (code < 0) {
6458             lastDownTime = FT_ApproxTime();     /* last time we tried an RPC */
6459             down = 1;
6460         }
6461         return code;
6462     }
6463
6464     /* otherwise convert to old format vldb entry */
6465     code = CopyVolumeEntry(avolid, &tve, avolinfo);
6466     return code;
6467 }
6468
6469
6470
6471
6472
6473
6474 afs_int32
6475 SRXAFS_GetVolumeInfo(struct rx_call * acall, char *avolid,
6476                      struct VolumeInfo * avolinfo)
6477 {
6478     afs_int32 code;
6479     struct rx_connection *tcon;
6480     struct host *thost;
6481 #if FS_STATS_DETAILED
6482     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6483     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6484     struct timeval elapsedTime; /* Transfer time */
6485
6486     /*
6487      * Set our stats pointer, remember when the RPC operation started, and
6488      * tally the operation.
6489      */
6490     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETVOLUMEINFO]);
6491     FS_LOCK;
6492     (opP->numOps)++;
6493     FS_UNLOCK;
6494     FT_GetTimeOfDay(&opStartTime, 0);
6495 #endif /* FS_STATS_DETAILED */
6496     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6497         goto Bad_GetVolumeInfo;
6498
6499     FS_LOCK;
6500     AFSCallStats.GetVolumeInfo++, AFSCallStats.TotalCalls++;
6501     FS_UNLOCK;
6502     code = TryLocalVLServer(avolid, avolinfo);
6503     ViceLog(1,
6504             ("SAFS_GetVolumeInfo returns %d, Volume %u, type %x, servers %x %x %x %x...\n",
6505              code, avolinfo->Vid, avolinfo->Type, avolinfo->Server0,
6506              avolinfo->Server1, avolinfo->Server2, avolinfo->Server3));
6507     avolinfo->Type4 = 0xabcd9999;       /* tell us to try new vldb */
6508
6509   Bad_GetVolumeInfo:
6510     code = CallPostamble(tcon, code, thost);
6511
6512 #if FS_STATS_DETAILED
6513     FT_GetTimeOfDay(&opStopTime, 0);
6514     if (code == 0) {
6515         FS_LOCK;
6516         (opP->numSuccesses)++;
6517         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6518         fs_stats_AddTo((opP->sumTime), elapsedTime);
6519         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6520         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6521             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6522         }
6523         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6524             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6525         }
6526         FS_UNLOCK;
6527     }
6528 #endif /* FS_STATS_DETAILED */
6529
6530     return code;
6531
6532 }                               /*SRXAFS_GetVolumeInfo */
6533
6534
6535 afs_int32
6536 SRXAFS_GetVolumeStatus(struct rx_call * acall, afs_int32 avolid,
6537                        AFSFetchVolumeStatus * FetchVolStatus, char **Name,
6538                        char **OfflineMsg, char **Motd)
6539 {
6540     Vnode *targetptr = 0;       /* vnode of the new file */
6541     Vnode *parentwhentargetnotdir = 0;  /* vnode of parent */
6542     Error errorCode = 0;                /* error code */
6543     Volume *volptr = 0;         /* pointer to the volume header */
6544     struct client *client = 0;  /* pointer to client entry */
6545     afs_int32 rights, anyrights;        /* rights for this and any user */
6546     AFSFid dummyFid;
6547     struct rx_connection *tcon;
6548     struct host *thost;
6549     struct client *t_client = NULL;     /* tmp ptr to client data */
6550 #if FS_STATS_DETAILED
6551     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6552     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6553     struct timeval elapsedTime; /* Transfer time */
6554
6555     /*
6556      * Set our stats pointer, remember when the RPC operation started, and
6557      * tally the operation.
6558      */
6559     opP =
6560         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETVOLUMESTATUS]);
6561     FS_LOCK;
6562     (opP->numOps)++;
6563     FS_UNLOCK;
6564     FT_GetTimeOfDay(&opStartTime, 0);
6565 #endif /* FS_STATS_DETAILED */
6566
6567     ViceLog(1, ("SAFS_GetVolumeStatus for volume %u\n", avolid));
6568     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6569         goto Bad_GetVolumeStatus;
6570
6571     FS_LOCK;
6572     AFSCallStats.GetVolumeStatus++, AFSCallStats.TotalCalls++;
6573     FS_UNLOCK;
6574     if (avolid == 0) {
6575         errorCode = EINVAL;
6576         goto Bad_GetVolumeStatus;
6577     }
6578     dummyFid.Volume = avolid, dummyFid.Vnode =
6579         (afs_int32) ROOTVNODE, dummyFid.Unique = 1;
6580
6581     if ((errorCode =
6582          GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr, MustBeDIR,
6583                           &parentwhentargetnotdir, &client, READ_LOCK,
6584                           &rights, &anyrights)))
6585         goto Bad_GetVolumeStatus;
6586
6587     if ((VanillaUser(client)) && (!(rights & PRSFS_READ))) {
6588         errorCode = EACCES;
6589         goto Bad_GetVolumeStatus;
6590     }
6591     (void)RXGetVolumeStatus(FetchVolStatus, Name, OfflineMsg, Motd, volptr);
6592
6593   Bad_GetVolumeStatus:
6594     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
6595                            volptr, &client);
6596     ViceLog(2, ("SAFS_GetVolumeStatus returns %d\n", errorCode));
6597     /* next is to guarantee out strings exist for stub */
6598     if (*Name == 0) {
6599         *Name = (char *)malloc(1);
6600         **Name = 0;
6601     }
6602     if (*Motd == 0) {
6603         *Motd = (char *)malloc(1);
6604         **Motd = 0;
6605     }
6606     if (*OfflineMsg == 0) {
6607         *OfflineMsg = (char *)malloc(1);
6608         **OfflineMsg = 0;
6609     }
6610     errorCode = CallPostamble(tcon, errorCode, thost);
6611
6612     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
6613
6614 #if FS_STATS_DETAILED
6615     FT_GetTimeOfDay(&opStopTime, 0);
6616     if (errorCode == 0) {
6617         FS_LOCK;
6618         (opP->numSuccesses)++;
6619         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6620         fs_stats_AddTo((opP->sumTime), elapsedTime);
6621         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6622         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6623             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6624         }
6625         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6626             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6627         }
6628         FS_UNLOCK;
6629     }
6630 #endif /* FS_STATS_DETAILED */
6631
6632     osi_auditU(acall, GetVolumeStatusEvent, errorCode, 
6633                AUD_ID, t_client ? t_client->ViceId : 0,
6634                AUD_LONG, avolid, AUD_STR, *Name, AUD_END);
6635     return (errorCode);
6636
6637 }                               /*SRXAFS_GetVolumeStatus */
6638
6639
6640 afs_int32
6641 SRXAFS_SetVolumeStatus(struct rx_call * acall, afs_int32 avolid,
6642                        AFSStoreVolumeStatus * StoreVolStatus, char *Name,
6643                        char *OfflineMsg, char *Motd)
6644 {
6645     Vnode *targetptr = 0;       /* vnode of the new file */
6646     Vnode *parentwhentargetnotdir = 0;  /* vnode of parent */
6647     Error errorCode = 0;                /* error code */
6648     Volume *volptr = 0;         /* pointer to the volume header */
6649     struct client *client = 0;  /* pointer to client entry */
6650     afs_int32 rights, anyrights;        /* rights for this and any user */
6651     AFSFid dummyFid;
6652     struct rx_connection *tcon = rx_ConnectionOf(acall);
6653     struct host *thost;
6654     struct client *t_client = NULL;     /* tmp ptr to client data */
6655 #if FS_STATS_DETAILED
6656     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6657     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6658     struct timeval elapsedTime; /* Transfer time */
6659
6660     /*
6661      * Set our stats pointer, remember when the RPC operation started, and
6662      * tally the operation.
6663      */
6664     opP =
6665         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SETVOLUMESTATUS]);
6666     FS_LOCK;
6667     (opP->numOps)++;
6668     FS_UNLOCK;
6669     FT_GetTimeOfDay(&opStartTime, 0);
6670 #endif /* FS_STATS_DETAILED */
6671
6672     ViceLog(1, ("SAFS_SetVolumeStatus for volume %u\n", avolid));
6673     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6674         goto Bad_SetVolumeStatus;
6675
6676     FS_LOCK;
6677     AFSCallStats.SetVolumeStatus++, AFSCallStats.TotalCalls++;
6678     FS_UNLOCK;
6679     if (avolid == 0) {
6680         errorCode = EINVAL;
6681         goto Bad_SetVolumeStatus;
6682     }
6683     dummyFid.Volume = avolid, dummyFid.Vnode =
6684         (afs_int32) ROOTVNODE, dummyFid.Unique = 1;
6685
6686     if ((errorCode =
6687          GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr, MustBeDIR,
6688                           &parentwhentargetnotdir, &client, READ_LOCK,
6689                           &rights, &anyrights)))
6690         goto Bad_SetVolumeStatus;
6691
6692     if (readonlyServer) {
6693         errorCode = VREADONLY;
6694         goto Bad_SetVolumeStatus;
6695     }
6696     if (VanillaUser(client)) {
6697         errorCode = EACCES;
6698         goto Bad_SetVolumeStatus;
6699     }
6700
6701     errorCode =
6702         RXUpdate_VolumeStatus(volptr, StoreVolStatus, Name, OfflineMsg, Motd);
6703
6704   Bad_SetVolumeStatus:
6705     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
6706                      volptr, &client);
6707     ViceLog(2, ("SAFS_SetVolumeStatus returns %d\n", errorCode));
6708     errorCode = CallPostamble(tcon, errorCode, thost);
6709
6710     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
6711
6712 #if FS_STATS_DETAILED
6713     FT_GetTimeOfDay(&opStopTime, 0);
6714     if (errorCode == 0) {
6715         FS_LOCK;
6716         (opP->numSuccesses)++;
6717         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6718         fs_stats_AddTo((opP->sumTime), elapsedTime);
6719         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6720         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6721             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6722         }
6723         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6724             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6725         }
6726         FS_UNLOCK;
6727     }
6728 #endif /* FS_STATS_DETAILED */
6729
6730     osi_auditU(acall, SetVolumeStatusEvent, errorCode, 
6731                AUD_ID, t_client ? t_client->ViceId : 0,
6732                AUD_LONG, avolid, AUD_STR, Name, AUD_END);
6733     return (errorCode);
6734 }                               /*SRXAFS_SetVolumeStatus */
6735
6736 #define DEFAULTVOLUME   "root.afs"
6737
6738 afs_int32
6739 SRXAFS_GetRootVolume(struct rx_call * acall, char **VolumeName)
6740 {
6741 #ifdef notdef
6742     int fd;
6743     int len;
6744     char *temp;
6745     struct rx_connection *tcon;
6746     struct host *thost;
6747     Error errorCode = 0;
6748 #endif
6749 #if FS_STATS_DETAILED
6750     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6751     struct timeval opStartTime; /* Start time for RPC op */
6752 #ifdef notdef
6753     struct timeval opStopTime;
6754     struct timeval elapsedTime; /* Transfer time */
6755 #endif
6756
6757     /*
6758      * Set our stats pointer, remember when the RPC operation started, and
6759      * tally the operation.
6760      */
6761     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETROOTVOLUME]);
6762     FS_LOCK;
6763     (opP->numOps)++;
6764     FS_UNLOCK;
6765     FT_GetTimeOfDay(&opStartTime, 0);
6766 #endif /* FS_STATS_DETAILED */
6767
6768     return FSERR_EOPNOTSUPP;
6769
6770 #ifdef  notdef
6771     if (errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost))
6772         goto Bad_GetRootVolume;
6773     FS_LOCK;
6774     AFSCallStats.GetRootVolume++, AFSCallStats.TotalCalls++;
6775     FS_UNLOCK;
6776     temp = malloc(256);
6777     fd = afs_open(AFSDIR_SERVER_ROOTVOL_FILEPATH, O_RDONLY, 0666);
6778     if (fd <= 0)
6779         strcpy(temp, DEFAULTVOLUME);
6780     else {
6781 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6782         lockf(fd, F_LOCK, 0);
6783 #else
6784         flock(fd, LOCK_EX);
6785 #endif
6786         len = read(fd, temp, 256);
6787 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6788         lockf(fd, F_ULOCK, 0);
6789 #else
6790         flock(fd, LOCK_UN);
6791 #endif
6792         close(fd);
6793         if (temp[len - 1] == '\n')
6794             len--;
6795         temp[len] = '\0';
6796     }
6797     *VolumeName = temp;         /* freed by rx server-side stub */
6798
6799   Bad_GetRootVolume:
6800     errorCode = CallPostamble(tcon, errorCode, thost);
6801
6802 #if FS_STATS_DETAILED
6803     FT_GetTimeOfDay(&opStopTime, 0);
6804     if (errorCode == 0) {
6805         FS_LOCK;
6806         (opP->numSuccesses)++;
6807         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6808         fs_stats_AddTo((opP->sumTime), elapsedTime);
6809         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6810         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6811             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6812         }
6813         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6814             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6815         }
6816         FS_UNLOCK;
6817     }
6818 #endif /* FS_STATS_DETAILED */
6819
6820     return (errorCode);
6821 #endif /* notdef */
6822
6823 }                               /*SRXAFS_GetRootVolume */
6824
6825
6826 /* still works because a struct CBS is the same as a struct AFSOpaque */
6827 afs_int32
6828 SRXAFS_CheckToken(struct rx_call * acall, afs_int32 AfsId,
6829                   struct AFSOpaque * Token)
6830 {
6831     afs_int32 code;
6832     struct rx_connection *tcon;
6833     struct host *thost;
6834 #if FS_STATS_DETAILED
6835     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6836     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6837     struct timeval elapsedTime; /* Transfer time */
6838
6839     /*
6840      * Set our stats pointer, remember when the RPC operation started, and
6841      * tally the operation.
6842      */
6843     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_CHECKTOKEN]);
6844     FS_LOCK;
6845     (opP->numOps)++;
6846     FS_UNLOCK;
6847     FT_GetTimeOfDay(&opStartTime, 0);
6848 #endif /* FS_STATS_DETAILED */
6849
6850     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6851         goto Bad_CheckToken;
6852
6853     code = FSERR_ECONNREFUSED;
6854
6855   Bad_CheckToken:
6856     code = CallPostamble(tcon, code, thost);
6857
6858 #if FS_STATS_DETAILED
6859     FT_GetTimeOfDay(&opStopTime, 0);
6860     if (code == 0) {
6861         FS_LOCK;
6862         (opP->numSuccesses)++;
6863         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6864         fs_stats_AddTo((opP->sumTime), elapsedTime);
6865         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6866         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6867             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6868         }
6869         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6870             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6871         }
6872         FS_UNLOCK;
6873     }
6874 #endif /* FS_STATS_DETAILED */
6875
6876     return code;
6877
6878 }                               /*SRXAFS_CheckToken */
6879
6880 afs_int32
6881 SRXAFS_GetTime(struct rx_call * acall, afs_uint32 * Seconds,
6882                afs_uint32 * USeconds)
6883 {
6884     afs_int32 code;
6885     struct rx_connection *tcon;
6886     struct host *thost;
6887     struct timeval tpl;
6888 #if FS_STATS_DETAILED
6889     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6890     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6891     struct timeval elapsedTime; /* Transfer time */
6892
6893     /*
6894      * Set our stats pointer, remember when the RPC operation started, and
6895      * tally the operation.
6896      */
6897     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETTIME]);
6898     FS_LOCK;
6899     (opP->numOps)++;
6900     FS_UNLOCK;
6901     FT_GetTimeOfDay(&opStartTime, 0);
6902 #endif /* FS_STATS_DETAILED */
6903
6904     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
6905         goto Bad_GetTime;
6906
6907     FS_LOCK;
6908     AFSCallStats.GetTime++, AFSCallStats.TotalCalls++;
6909     FS_UNLOCK;
6910     FT_GetTimeOfDay(&tpl, 0);
6911     *Seconds = tpl.tv_sec;
6912     *USeconds = tpl.tv_usec;
6913
6914     ViceLog(2, ("SAFS_GetTime returns %u, %u\n", *Seconds, *USeconds));
6915
6916   Bad_GetTime:
6917     code = CallPostamble(tcon, code, thost);
6918
6919 #if FS_STATS_DETAILED
6920     FT_GetTimeOfDay(&opStopTime, 0);
6921     fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6922     if (code == 0) {
6923         FS_LOCK;
6924         (opP->numSuccesses)++;
6925         fs_stats_AddTo((opP->sumTime), elapsedTime);
6926         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6927         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6928             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6929         }
6930         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6931             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6932         }
6933         FS_UNLOCK;
6934     }
6935 #endif /* FS_STATS_DETAILED */
6936
6937     return code;
6938
6939 }                               /*SRXAFS_GetTime */
6940
6941
6942 /*
6943  * FetchData_RXStyle
6944  *
6945  * Purpose:
6946  *      Implement a client's data fetch using Rx.
6947  *
6948  * Arguments:
6949  *      volptr          : Ptr to the given volume's info.
6950  *      targetptr       : Pointer to the vnode involved.
6951  *      Call            : Ptr to the Rx call involved.
6952  *      Pos             : Offset within the file.
6953  *      Len             : Length in bytes to read; this value is bogus!
6954  * if FS_STATS_DETAILED
6955  *      a_bytesToFetchP : Set to the number of bytes to be fetched from
6956  *                        the File Server.
6957  *      a_bytesFetchedP : Set to the actual number of bytes fetched from
6958  *                        the File Server.
6959  * endif
6960  */
6961
6962 afs_int32
6963 FetchData_RXStyle(Volume * volptr, Vnode * targetptr,
6964                   register struct rx_call * Call, afs_sfsize_t Pos,
6965                   afs_sfsize_t Len, afs_int32 Int64Mode,
6966 #if FS_STATS_DETAILED
6967                   afs_sfsize_t * a_bytesToFetchP,
6968                   afs_sfsize_t * a_bytesFetchedP
6969 #endif                          /* FS_STATS_DETAILED */
6970     )
6971 {
6972     struct timeval StartTime, StopTime; /* used to calculate file  transfer rates */
6973     Error errorCode = 0;                /* Returned error code to caller */
6974     IHandle_t *ihP;
6975     FdHandle_t *fdP;
6976 #ifdef AFS_NT40_ENV
6977     register char *tbuffer;
6978 #else /* AFS_NT40_ENV */
6979     struct iovec tiov[RX_MAXIOVECS];
6980     int tnio;
6981 #endif /* AFS_NT40_ENV */
6982     afs_sfsize_t tlen;
6983     afs_int32 optSize;
6984
6985 #if FS_STATS_DETAILED
6986     /*
6987      * Initialize the byte count arguments.
6988      */
6989     (*a_bytesToFetchP) = 0;
6990     (*a_bytesFetchedP) = 0;
6991 #endif /* FS_STATS_DETAILED */
6992
6993
6994     ViceLog(25,
6995             ("FetchData_RXStyle: Pos %llu, Len %llu\n", (afs_uintmax_t) Pos,
6996              (afs_uintmax_t) Len));
6997
6998     if (!VN_GET_INO(targetptr)) {
6999         afs_int32 zero = htonl(0);
7000         /*
7001          * This is used for newly created files; we simply send 0 bytes
7002          * back to make the cache manager happy...
7003          */
7004         if (Int64Mode)
7005             rx_Write(Call, (char *)&zero, sizeof(afs_int32));   /* send 0-length  */
7006         rx_Write(Call, (char *)&zero, sizeof(afs_int32));       /* send 0-length  */
7007         return (0);
7008     }
7009     FT_GetTimeOfDay(&StartTime, 0);
7010     ihP = targetptr->handle;
7011     fdP = IH_OPEN(ihP);
7012     if (fdP == NULL) {
7013         VTakeOffline(volptr);
7014         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7015                     volptr->hashid));
7016         return EIO;
7017     }
7018     optSize = sendBufSize;
7019     tlen = FDH_SIZE(fdP);
7020     ViceLog(25,
7021             ("FetchData_RXStyle: file size %llu\n", (afs_uintmax_t) tlen));
7022     if (tlen < 0) {
7023         FDH_CLOSE(fdP);
7024         VTakeOffline(volptr);
7025         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7026                     volptr->hashid));
7027         return EIO;
7028     }
7029     if (Pos > tlen) {
7030         Len = 0;
7031     }
7032
7033     if (Pos + Len > tlen) /* get length we should send */
7034         Len = ((tlen - Pos) < 0) ? 0 : tlen - Pos;
7035
7036     (void)FDH_SEEK(fdP, Pos, 0);
7037     {
7038         afs_int32 high, low;
7039         SplitOffsetOrSize(Len, high, low);
7040         assert(Int64Mode || (Len >= 0 && high == 0) || Len < 0);
7041         if (Int64Mode) {
7042             high = htonl(high);
7043             rx_Write(Call, (char *)&high, sizeof(afs_int32));   /* High order bits */
7044         }
7045         low = htonl(low);
7046         rx_Write(Call, (char *)&low, sizeof(afs_int32));        /* send length on fetch */
7047     }
7048 #if FS_STATS_DETAILED
7049     (*a_bytesToFetchP) = Len;
7050 #endif /* FS_STATS_DETAILED */
7051 #ifdef AFS_NT40_ENV
7052     tbuffer = AllocSendBuffer();
7053 #endif /* AFS_NT40_ENV */
7054     while (Len > 0) {
7055         int wlen;
7056         if (Len > optSize)
7057             wlen = optSize;
7058         else
7059             wlen = (int)Len;
7060 #ifdef AFS_NT40_ENV
7061         errorCode = FDH_READ(fdP, tbuffer, wlen);
7062         if (errorCode != wlen) {
7063             FDH_CLOSE(fdP);
7064             FreeSendBuffer((struct afs_buffer *)tbuffer);
7065             VTakeOffline(volptr);
7066             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7067                         volptr->hashid));
7068             return EIO;
7069         }
7070         errorCode = rx_Write(Call, tbuffer, wlen);
7071 #else /* AFS_NT40_ENV */
7072         errorCode = rx_WritevAlloc(Call, tiov, &tnio, RX_MAXIOVECS, wlen);
7073         if (errorCode <= 0) {
7074             FDH_CLOSE(fdP);
7075             return EIO;
7076         }
7077         wlen = errorCode;
7078         errorCode = FDH_READV(fdP, tiov, tnio);
7079         if (errorCode != wlen) {
7080             FDH_CLOSE(fdP);
7081             VTakeOffline(volptr);
7082             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7083                         volptr->hashid));
7084             return EIO;
7085         }
7086         errorCode = rx_Writev(Call, tiov, tnio, wlen);
7087 #endif /* AFS_NT40_ENV */
7088 #if FS_STATS_DETAILED
7089         /*
7090          * Bump the number of bytes actually sent by the number from this
7091          * latest iteration
7092          */
7093         (*a_bytesFetchedP) += errorCode;
7094 #endif /* FS_STATS_DETAILED */
7095         if (errorCode != wlen) {
7096             FDH_CLOSE(fdP);
7097 #ifdef AFS_NT40_ENV
7098             FreeSendBuffer((struct afs_buffer *)tbuffer);
7099 #endif /* AFS_NT40_ENV */
7100             return -31;
7101         }
7102         Len -= wlen;
7103     }
7104 #ifdef AFS_NT40_ENV
7105     FreeSendBuffer((struct afs_buffer *)tbuffer);
7106 #endif /* AFS_NT40_ENV */
7107     FDH_CLOSE(fdP);
7108     FT_GetTimeOfDay(&StopTime, 0);
7109
7110     /* Adjust all Fetch Data related stats */
7111     FS_LOCK;
7112     if (AFSCallStats.TotalFetchedBytes > 2000000000)    /* Reset if over 2 billion */
7113         AFSCallStats.TotalFetchedBytes = AFSCallStats.AccumFetchTime = 0;
7114     AFSCallStats.AccumFetchTime +=
7115         ((StopTime.tv_sec - StartTime.tv_sec) * 1000) +
7116         ((StopTime.tv_usec - StartTime.tv_usec) / 1000);
7117     {
7118         afs_fsize_t targLen;
7119         VN_GET_LEN(targLen, targetptr);
7120         AFSCallStats.TotalFetchedBytes += targLen;
7121         AFSCallStats.FetchSize1++;
7122         if (targLen < SIZE2)
7123             AFSCallStats.FetchSize2++;
7124         else if (targLen < SIZE3)
7125             AFSCallStats.FetchSize3++;
7126         else if (targLen < SIZE4)
7127             AFSCallStats.FetchSize4++;
7128         else
7129             AFSCallStats.FetchSize5++;
7130     }
7131     FS_UNLOCK;
7132     return (0);
7133
7134 }                               /*FetchData_RXStyle */
7135
7136 static int
7137 GetLinkCountAndSize(Volume * vp, FdHandle_t * fdP, int *lc,
7138                     afs_sfsize_t * size)
7139 {
7140 #ifdef AFS_NAMEI_ENV
7141     FdHandle_t *lhp;
7142     lhp = IH_OPEN(V_linkHandle(vp));
7143     if (!lhp)
7144         return EIO;
7145 #ifdef AFS_NT40_ENV
7146     *lc = nt_GetLinkCount(lhp, fdP->fd_ih->ih_ino, 0);
7147 #else
7148     *lc = namei_GetLinkCount(lhp, fdP->fd_ih->ih_ino, 0);
7149 #endif
7150     FDH_CLOSE(lhp);
7151     if (*lc < 0)
7152         return -1;
7153     *size = OS_SIZE(fdP->fd_fd);
7154     return (*size == -1) ? -1 : 0;
7155 #else
7156     struct afs_stat status;
7157
7158     if (afs_fstat(fdP->fd_fd, &status) < 0) {
7159         return -1;
7160     }
7161
7162     *lc = GetLinkCount(vp, &status);
7163     *size = status.st_size;
7164     return 0;
7165 #endif
7166 }
7167
7168 /*
7169  * StoreData_RXStyle
7170  *
7171  * Purpose:
7172  *      Implement a client's data store using Rx.
7173  *
7174  * Arguments:
7175  *      volptr          : Ptr to the given volume's info.
7176  *      targetptr       : Pointer to the vnode involved.
7177  *      Call            : Ptr to the Rx call involved.
7178  *      Pos             : Offset within the file.
7179  *      Len             : Length in bytes to store; this value is bogus!
7180  * if FS_STATS_DETAILED
7181  *      a_bytesToStoreP : Set to the number of bytes to be stored to
7182  *                        the File Server.
7183  *      a_bytesStoredP  : Set to the actual number of bytes stored to
7184  *                        the File Server.
7185  * endif
7186  */
7187 afs_int32
7188 StoreData_RXStyle(Volume * volptr, Vnode * targetptr, struct AFSFid * Fid,
7189                   struct client * client, register struct rx_call * Call,
7190                   afs_fsize_t Pos, afs_fsize_t Length, afs_fsize_t FileLength,
7191                   int sync,
7192 #if FS_STATS_DETAILED
7193                   afs_sfsize_t * a_bytesToStoreP,
7194                   afs_sfsize_t * a_bytesStoredP
7195 #endif                          /* FS_STATS_DETAILED */
7196     )
7197 {
7198     afs_sfsize_t bytesTransfered;       /* number of bytes actually transfered */
7199     struct timeval StartTime, StopTime; /* Used to measure how long the store takes */
7200     Error errorCode = 0;                /* Returned error code to caller */
7201 #ifdef AFS_NT40_ENV
7202     register char *tbuffer;     /* data copying buffer */
7203 #else /* AFS_NT40_ENV */
7204     struct iovec tiov[RX_MAXIOVECS];    /* no data copying with iovec */
7205     int tnio;                   /* temp for iovec size */
7206 #endif /* AFS_NT40_ENV */
7207     afs_sfsize_t tlen;          /* temp for xfr length */
7208     Inode tinode;               /* inode for I/O */
7209     afs_int32 optSize;          /* optimal transfer size */
7210     afs_sfsize_t DataLength = 0;        /* size of inode */
7211     afs_sfsize_t TruncatedLength;       /* size after ftruncate */
7212     afs_fsize_t NewLength;      /* size after this store completes */
7213     afs_sfsize_t adjustSize;    /* bytes to call VAdjust... with */
7214     int linkCount = 0;          /* link count on inode */
7215     afs_fsize_t CoW_off, CoW_len;
7216     FdHandle_t *fdP, *origfdP = NULL;
7217     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
7218
7219 #if FS_STATS_DETAILED
7220     /*
7221      * Initialize the byte count arguments.
7222      */
7223     (*a_bytesToStoreP) = 0;
7224     (*a_bytesStoredP) = 0;
7225 #endif /* FS_STATS_DETAILED */
7226
7227     /*
7228      * We break the callbacks here so that the following signal will not
7229      * leave a window.
7230      */
7231     BreakCallBack(client->host, Fid, 0);
7232
7233     if (Pos == -1 || VN_GET_INO(targetptr) == 0) {
7234         /* the inode should have been created in Alloc_NewVnode */
7235         logHostAddr.s_addr = rxr_HostOf(rx_ConnectionOf(Call));
7236         ViceLog(0,
7237                 ("StoreData_RXStyle : Inode non-existent Fid = %u.%u.%u, inode = %llu, Pos %llu Host %s:%d\n",
7238                  Fid->Volume, Fid->Vnode, Fid->Unique,
7239                  (afs_uintmax_t) VN_GET_INO(targetptr), (afs_uintmax_t) Pos,
7240                  inet_ntoa(logHostAddr), ntohs(rxr_PortOf(rx_ConnectionOf(Call)))));
7241         return ENOENT;          /* is this proper error code? */
7242     } else {
7243         /*
7244          * See if the file has several links (from other volumes).  If it
7245          * does, then we have to make a copy before changing it to avoid
7246          *changing read-only clones of this dude
7247          */
7248         ViceLog(25,
7249                 ("StoreData_RXStyle : Opening inode %s\n",
7250                  PrintInode(NULL, VN_GET_INO(targetptr))));
7251         fdP = IH_OPEN(targetptr->handle);
7252         if (fdP == NULL)
7253             return ENOENT;
7254         if (GetLinkCountAndSize(volptr, fdP, &linkCount, &DataLength) < 0) {
7255             FDH_CLOSE(fdP);
7256             VTakeOffline(volptr);
7257             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7258                         volptr->hashid));
7259             return EIO;
7260         }
7261
7262         if (linkCount != 1) {
7263             afs_fsize_t size;
7264             ViceLog(25,
7265                     ("StoreData_RXStyle : inode %s has more than onelink\n",
7266                      PrintInode(NULL, VN_GET_INO(targetptr))));
7267             /* other volumes share this data, better copy it first */
7268
7269             /* Adjust the disk block count by the creation of the new inode.
7270              * We call the special VDiskUsage so we don't adjust the volume's
7271              * quota since we don't want to penalyze the user for afs's internal
7272              * mechanisms (i.e. copy on write overhead.) Also the right size
7273              * of the disk will be recorded...
7274              */
7275             origfdP = fdP;
7276             VN_GET_LEN(size, targetptr);
7277             volptr->partition->flags &= ~PART_DONTUPDATE;
7278             VSetPartitionDiskUsage(volptr->partition);
7279             volptr->partition->flags |= PART_DONTUPDATE;
7280             if ((errorCode = VDiskUsage(volptr, nBlocks(size)))) {
7281                 volptr->partition->flags &= ~PART_DONTUPDATE;
7282                 FDH_CLOSE(origfdP);
7283                 return (errorCode);
7284             }
7285
7286             CoW_len = (FileLength >= (Length + Pos)) ? FileLength - Length : Pos;
7287             CopyOnWrite_calls++;
7288             if (CoW_len == 0) CopyOnWrite_size0++;
7289             if (Pos == 0) CopyOnWrite_off0++;
7290             if (CoW_len > CopyOnWrite_maxsize) CopyOnWrite_maxsize = CoW_len;
7291
7292             ViceLog(1, ("StoreData : calling CopyOnWrite on vnode %u.%u (%s) "
7293                         "off 0x0 size 0x%llx\n",
7294                         afs_printable_VolumeId_u(V_id(volptr)),
7295                         afs_printable_VnodeId_u(targetptr->vnodeNumber),
7296                         V_name(volptr), Pos));
7297             if ((errorCode = CopyOnWrite(targetptr, volptr, 0, Pos))) {
7298                 ViceLog(25, ("StoreData : CopyOnWrite failed\n"));
7299                 volptr->partition->flags &= ~PART_DONTUPDATE;
7300                 FDH_CLOSE(origfdP);
7301                 return (errorCode);
7302             }
7303             volptr->partition->flags &= ~PART_DONTUPDATE;
7304             VSetPartitionDiskUsage(volptr->partition);
7305             fdP = IH_OPEN(targetptr->handle);
7306             if (fdP == NULL) {
7307                 ViceLog(25,
7308                         ("StoreData : Reopen after CopyOnWrite failed\n"));
7309                 FDH_CLOSE(origfdP);
7310                 return ENOENT;
7311             }
7312         }
7313         tinode = VN_GET_INO(targetptr);
7314     }
7315     if (!VALID_INO(tinode)) {
7316         VTakeOffline(volptr);
7317         ViceLog(0,("Volume %u now offline, must be salvaged.\n",
7318                    volptr->hashid));
7319         return EIO;
7320     }
7321
7322     /* compute new file length */
7323     NewLength = DataLength;
7324     if (FileLength < NewLength)
7325         /* simulate truncate */
7326         NewLength = FileLength;
7327     TruncatedLength = NewLength;        /* remember length after possible ftruncate */
7328     if (Pos + Length > NewLength)
7329         NewLength = Pos + Length;       /* and write */
7330
7331     /* adjust the disk block count by the difference in the files */
7332     {
7333         afs_fsize_t targSize;
7334         VN_GET_LEN(targSize, targetptr);
7335         adjustSize = nBlocks(NewLength) - nBlocks(targSize);
7336     }
7337     if ((errorCode =
7338          AdjustDiskUsage(volptr, adjustSize,
7339                          adjustSize - SpareComp(volptr)))) {
7340         FDH_CLOSE(fdP);
7341         if (origfdP) FDH_CLOSE(origfdP);
7342         return (errorCode);
7343     }
7344
7345     /* can signal cache manager to proceed from close now */
7346     /* this bit means that the locks are set and protections are OK */
7347     rx_SetLocalStatus(Call, 1);
7348
7349     FT_GetTimeOfDay(&StartTime, 0);
7350
7351     optSize = sendBufSize;
7352     ViceLog(25,
7353             ("StoreData_RXStyle: Pos %llu, DataLength %llu, FileLength %llu, Length %llu\n",
7354              (afs_uintmax_t) Pos, (afs_uintmax_t) DataLength,
7355              (afs_uintmax_t) FileLength, (afs_uintmax_t) Length));
7356
7357     /* truncate the file iff it needs it (ftruncate is slow even when its a noop) */
7358     if (FileLength < DataLength)
7359         FDH_TRUNC(fdP, FileLength);
7360     if (Pos > 0)
7361         FDH_SEEK(fdP, Pos, 0);
7362     bytesTransfered = 0;
7363 #ifdef AFS_NT40_ENV
7364     tbuffer = AllocSendBuffer();
7365 #endif /* AFS_NT40_ENV */
7366     /* if length == 0, the loop below isn't going to do anything, including
7367      * extend the length of the inode, which it must do, since the file system
7368      * assumes that the inode length == vnode's file length.  So, we extend
7369      * the file length manually if need be.  Note that if file is bigger than
7370      * Pos+(Length==0), we dont' have to do anything, and certainly shouldn't
7371      * do what we're going to do below.
7372      */
7373     if (Length == 0 && Pos > TruncatedLength) {
7374         /* Set the file's length; we've already done an lseek to the right
7375          * spot above.
7376          */
7377         errorCode = FDH_WRITE(fdP, &tlen, 1);
7378         if (errorCode != 1)
7379             goto done;
7380         errorCode = FDH_TRUNC(fdP, Pos);
7381     } else {
7382         /* have some data to copy */
7383 #if FS_STATS_DETAILED
7384         (*a_bytesToStoreP) = Length;
7385 #endif /* FS_STATS_DETAILED */
7386         while (1) {
7387             int rlen;
7388             if (bytesTransfered >= Length) {
7389                 errorCode = 0;
7390                 break;
7391             }
7392             tlen = Length - bytesTransfered;    /* how much more to do */
7393             if (tlen > optSize)
7394                 rlen = optSize; /* bound by buffer size */
7395             else
7396                 rlen = (int)tlen;
7397 #ifdef AFS_NT40_ENV
7398             errorCode = rx_Read(Call, tbuffer, rlen);
7399 #else /* AFS_NT40_ENV */
7400             errorCode = rx_Readv(Call, tiov, &tnio, RX_MAXIOVECS, rlen);
7401 #endif /* AFS_NT40_ENV */
7402             if (errorCode <= 0) {
7403                 errorCode = -32;
7404                 break;
7405             }
7406 #if FS_STATS_DETAILED
7407             (*a_bytesStoredP) += errorCode;
7408 #endif /* FS_STATS_DETAILED */
7409             rlen = errorCode;
7410 #ifdef AFS_NT40_ENV
7411             errorCode = FDH_WRITE(fdP, tbuffer, rlen);
7412 #else /* AFS_NT40_ENV */
7413             errorCode = FDH_WRITEV(fdP, tiov, tnio);
7414 #endif /* AFS_NT40_ENV */
7415             if (errorCode != rlen) {
7416                 errorCode = VDISKFULL;
7417                 break;
7418             }
7419             bytesTransfered += rlen;
7420         }
7421     }
7422   done:
7423 #ifdef AFS_NT40_ENV
7424     FreeSendBuffer((struct afs_buffer *)tbuffer);
7425 #endif /* AFS_NT40_ENV */
7426     if (sync) {
7427         FDH_SYNC(fdP);
7428     }
7429     if (errorCode) {
7430         afs_fsize_t nfSize = (afs_fsize_t) FDH_SIZE(fdP);
7431         /* something went wrong: adjust size and return */
7432         VN_SET_LEN(targetptr, nfSize);  /* set new file size. */
7433         /* changed_newTime is tested in StoreData to detemine if we
7434          * need to update the target vnode.
7435          */
7436         targetptr->changed_newTime = 1;
7437         if (origfdP && (bytesTransfered < Length))      /* Need to "finish" CopyOnWrite still */
7438             CopyOnWrite2(origfdP, fdP, Pos + bytesTransfered, NewLength - Pos - bytesTransfered);
7439         if (origfdP) FDH_CLOSE(origfdP);
7440         FDH_CLOSE(fdP);
7441         /* set disk usage to be correct */
7442         VAdjustDiskUsage(&errorCode, volptr,
7443                          (afs_sfsize_t) (nBlocks(nfSize) -
7444                                          nBlocks(NewLength)), 0);
7445         return errorCode;
7446     }
7447     if (origfdP) {                                      /* finish CopyOnWrite */
7448         if ( (CoW_off = Pos + Length) < NewLength) {
7449             errorCode = CopyOnWrite2(origfdP, fdP, CoW_off, CoW_len = NewLength - CoW_off);
7450             ViceLog(1, ("StoreData : CopyOnWrite2 on vnode %u.%u (%s) "
7451                         "off 0x%llx size 0x%llx returns %d\n",
7452                         afs_printable_VolumeId_u(V_id(volptr)),
7453                         afs_printable_VnodeId_u(targetptr->vnodeNumber),
7454                         V_name(volptr), CoW_off, CoW_len, errorCode));
7455         }
7456         FDH_CLOSE(origfdP);
7457     }
7458     FDH_CLOSE(fdP);
7459
7460     FT_GetTimeOfDay(&StopTime, 0);
7461
7462     VN_SET_LEN(targetptr, NewLength);
7463
7464     /* Update all StoreData related stats */
7465     FS_LOCK;
7466     if (AFSCallStats.TotalStoredBytes > 2000000000)     /* reset if over 2 billion */
7467         AFSCallStats.TotalStoredBytes = AFSCallStats.AccumStoreTime = 0;
7468     AFSCallStats.StoreSize1++;  /* Piggybacked data */
7469     {
7470         afs_fsize_t targLen;
7471         VN_GET_LEN(targLen, targetptr);
7472         if (targLen < SIZE2)
7473             AFSCallStats.StoreSize2++;
7474         else if (targLen < SIZE3)
7475             AFSCallStats.StoreSize3++;
7476         else if (targLen < SIZE4)
7477             AFSCallStats.StoreSize4++;
7478         else
7479             AFSCallStats.StoreSize5++;
7480     }
7481     FS_UNLOCK;
7482     return (errorCode);
7483
7484 }                               /*StoreData_RXStyle */
7485
7486 static int sys2et[512];
7487
7488 void
7489 init_sys_error_to_et(void)
7490 {
7491     memset(&sys2et, 0, sizeof(sys2et));
7492     sys2et[EPERM] = UAEPERM;
7493     sys2et[ENOENT] = UAENOENT;
7494     sys2et[ESRCH] = UAESRCH;
7495     sys2et[EINTR] = UAEINTR;
7496     sys2et[EIO] = UAEIO;
7497     sys2et[ENXIO] = UAENXIO;
7498     sys2et[E2BIG] = UAE2BIG;
7499     sys2et[ENOEXEC] = UAENOEXEC;
7500     sys2et[EBADF] = UAEBADF;
7501     sys2et[ECHILD] = UAECHILD;
7502     sys2et[EAGAIN] = UAEAGAIN;
7503     sys2et[ENOMEM] = UAENOMEM;
7504     sys2et[EACCES] = UAEACCES;
7505     sys2et[EFAULT] = UAEFAULT;
7506     sys2et[ENOTBLK] = UAENOTBLK;
7507     sys2et[EBUSY] = UAEBUSY;
7508     sys2et[EEXIST] = UAEEXIST;
7509     sys2et[EXDEV] = UAEXDEV;
7510     sys2et[ENODEV] = UAENODEV;
7511     sys2et[ENOTDIR] = UAENOTDIR;
7512     sys2et[EISDIR] = UAEISDIR;
7513     sys2et[EINVAL] = UAEINVAL;
7514     sys2et[ENFILE] = UAENFILE;
7515     sys2et[EMFILE] = UAEMFILE;
7516     sys2et[ENOTTY] = UAENOTTY;
7517     sys2et[ETXTBSY] = UAETXTBSY;
7518     sys2et[EFBIG] = UAEFBIG;
7519     sys2et[ENOSPC] = UAENOSPC;
7520     sys2et[ESPIPE] = UAESPIPE;
7521     sys2et[EROFS] = UAEROFS;
7522     sys2et[EMLINK] = UAEMLINK;
7523     sys2et[EPIPE] = UAEPIPE;
7524     sys2et[EDOM] = UAEDOM;
7525     sys2et[ERANGE] = UAERANGE;
7526     sys2et[EDEADLK] = UAEDEADLK;
7527     sys2et[ENAMETOOLONG] = UAENAMETOOLONG;
7528     sys2et[ENOLCK] = UAENOLCK;
7529     sys2et[ENOSYS] = UAENOSYS;
7530 #if (ENOTEMPTY != EEXIST)
7531     sys2et[ENOTEMPTY] = UAENOTEMPTY;
7532 #endif
7533     sys2et[ELOOP] = UAELOOP;
7534 #if (EWOULDBLOCK != EAGAIN)
7535     sys2et[EWOULDBLOCK] = UAEWOULDBLOCK;
7536 #endif
7537     sys2et[ENOMSG] = UAENOMSG;
7538     sys2et[EIDRM] = UAEIDRM;
7539     sys2et[ECHRNG] = UAECHRNG;
7540     sys2et[EL2NSYNC] = UAEL2NSYNC;
7541     sys2et[EL3HLT] = UAEL3HLT;
7542     sys2et[EL3RST] = UAEL3RST;
7543     sys2et[ELNRNG] = UAELNRNG;
7544     sys2et[EUNATCH] = UAEUNATCH;
7545     sys2et[ENOCSI] = UAENOCSI;
7546     sys2et[EL2HLT] = UAEL2HLT;
7547     sys2et[EBADE] = UAEBADE;
7548     sys2et[EBADR] = UAEBADR;
7549     sys2et[EXFULL] = UAEXFULL;
7550     sys2et[ENOANO] = UAENOANO;
7551     sys2et[EBADRQC] = UAEBADRQC;
7552     sys2et[EBADSLT] = UAEBADSLT;
7553     sys2et[EDEADLK] = UAEDEADLK;
7554     sys2et[EBFONT] = UAEBFONT;
7555     sys2et[ENOSTR] = UAENOSTR;
7556     sys2et[ENODATA] = UAENODATA;
7557     sys2et[ETIME] = UAETIME;
7558     sys2et[ENOSR] = UAENOSR;
7559     sys2et[ENONET] = UAENONET;
7560     sys2et[ENOPKG] = UAENOPKG;
7561     sys2et[EREMOTE] = UAEREMOTE;
7562     sys2et[ENOLINK] = UAENOLINK;
7563     sys2et[EADV] = UAEADV;
7564     sys2et[ESRMNT] = UAESRMNT;
7565     sys2et[ECOMM] = UAECOMM;
7566     sys2et[EPROTO] = UAEPROTO;
7567     sys2et[EMULTIHOP] = UAEMULTIHOP;
7568     sys2et[EDOTDOT] = UAEDOTDOT;
7569     sys2et[EBADMSG] = UAEBADMSG;
7570     sys2et[EOVERFLOW] = UAEOVERFLOW;
7571     sys2et[ENOTUNIQ] = UAENOTUNIQ;
7572     sys2et[EBADFD] = UAEBADFD;
7573     sys2et[EREMCHG] = UAEREMCHG;
7574     sys2et[ELIBACC] = UAELIBACC;
7575     sys2et[ELIBBAD] = UAELIBBAD;
7576     sys2et[ELIBSCN] = UAELIBSCN;
7577     sys2et[ELIBMAX] = UAELIBMAX;
7578     sys2et[ELIBEXEC] = UAELIBEXEC;
7579     sys2et[EILSEQ] = UAEILSEQ;
7580     sys2et[ERESTART] = UAERESTART;
7581     sys2et[ESTRPIPE] = UAESTRPIPE;
7582     sys2et[EUSERS] = UAEUSERS;
7583     sys2et[ENOTSOCK] = UAENOTSOCK;
7584     sys2et[EDESTADDRREQ] = UAEDESTADDRREQ;
7585     sys2et[EMSGSIZE] = UAEMSGSIZE;
7586     sys2et[EPROTOTYPE] = UAEPROTOTYPE;
7587     sys2et[ENOPROTOOPT] = UAENOPROTOOPT;
7588     sys2et[EPROTONOSUPPORT] = UAEPROTONOSUPPORT;
7589     sys2et[ESOCKTNOSUPPORT] = UAESOCKTNOSUPPORT;
7590     sys2et[EOPNOTSUPP] = UAEOPNOTSUPP;
7591     sys2et[EPFNOSUPPORT] = UAEPFNOSUPPORT;
7592     sys2et[EAFNOSUPPORT] = UAEAFNOSUPPORT;
7593     sys2et[EADDRINUSE] = UAEADDRINUSE;
7594     sys2et[EADDRNOTAVAIL] = UAEADDRNOTAVAIL;
7595     sys2et[ENETDOWN] = UAENETDOWN;
7596     sys2et[ENETUNREACH] = UAENETUNREACH;
7597     sys2et[ENETRESET] = UAENETRESET;
7598     sys2et[ECONNABORTED] = UAECONNABORTED;
7599     sys2et[ECONNRESET] = UAECONNRESET;
7600     sys2et[ENOBUFS] = UAENOBUFS;
7601     sys2et[EISCONN] = UAEISCONN;
7602     sys2et[ENOTCONN] = UAENOTCONN;
7603     sys2et[ESHUTDOWN] = UAESHUTDOWN;
7604     sys2et[ETOOMANYREFS] = UAETOOMANYREFS;
7605     sys2et[ETIMEDOUT] = UAETIMEDOUT;
7606     sys2et[ECONNREFUSED] = UAECONNREFUSED;
7607     sys2et[EHOSTDOWN] = UAEHOSTDOWN;
7608     sys2et[EHOSTUNREACH] = UAEHOSTUNREACH;
7609     sys2et[EALREADY] = UAEALREADY;
7610     sys2et[EINPROGRESS] = UAEINPROGRESS;
7611     sys2et[ESTALE] = UAESTALE;
7612     sys2et[EUCLEAN] = UAEUCLEAN;
7613     sys2et[ENOTNAM] = UAENOTNAM;
7614     sys2et[ENAVAIL] = UAENAVAIL;
7615     sys2et[EISNAM] = UAEISNAM;
7616     sys2et[EREMOTEIO] = UAEREMOTEIO;
7617     sys2et[EDQUOT] = UAEDQUOT;
7618     sys2et[ENOMEDIUM] = UAENOMEDIUM;
7619     sys2et[EMEDIUMTYPE] = UAEMEDIUMTYPE;
7620
7621     sys2et[EIO] = UAEIO;
7622 }
7623
7624 /* NOTE:  2006-03-01                                                     
7625  *  SRXAFS_CallBackRxConnAddr should be re-written as follows:           
7626  *  - pass back the connection, client, and host from CallPreamble       
7627  *  - keep a ref on the client, which we don't now                       
7628  *  - keep a hold on the host, which we already do                       
7629  *  - pass the connection, client, and host down into SAFSS_*, and use   
7630  *    them instead of independently discovering them via rx_ConnectionOf 
7631  *    (safe) and rx_GetSpecific (not so safe)                            
7632  *  The idea being that we decide what client and host we're going to use
7633  *  when CallPreamble is called, and stay consistent throughout the call.
7634  *  This change is too invasive for 1.4.1 but should be made in 1.5.x.   
7635  */                                                                      
7636
7637 afs_int32
7638 SRXAFS_CallBackRxConnAddr (struct rx_call * acall, afs_int32 *addr)
7639 {
7640     Error errorCode = 0;
7641     struct rx_connection *tcon;
7642     struct host *tcallhost;
7643 #ifdef __EXPERIMENTAL_CALLBACK_CONN_MOVING
7644     struct host *thost;
7645     struct client *tclient;
7646     static struct rx_securityClass *sc = 0;
7647     int i,j;
7648     struct rx_connection *conn;
7649 #endif
7650     
7651     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &tcallhost)))
7652             goto Bad_CallBackRxConnAddr1;
7653     
7654 #ifndef __EXPERIMENTAL_CALLBACK_CONN_MOVING
7655     errorCode = 1;
7656 #else
7657     H_LOCK;
7658     tclient = h_FindClient_r(tcon);
7659     if (!tclient) {
7660         errorCode = VBUSY;
7661         goto Bad_CallBackRxConnAddr;
7662     }
7663     thost = tclient->host;
7664     
7665     /* nothing more can be done */
7666     if ( !thost->interface ) 
7667         goto Bad_CallBackRxConnAddr;
7668     
7669     /* the only address is the primary interface */
7670     /* can't change when there's only 1 address, anyway */
7671     if ( thost->interface->numberOfInterfaces <= 1 ) 
7672         goto Bad_CallBackRxConnAddr;
7673     
7674     /* initialise a security object only once */
7675     if ( !sc )
7676         sc = (struct rx_securityClass *) rxnull_NewClientSecurityObject();
7677     
7678     for ( i=0; i < thost->interface->numberOfInterfaces; i++)
7679     {
7680             if ( *addr == thost->interface->addr[i] ) {
7681                     break;
7682             }
7683     }
7684     
7685     if ( *addr != thost->interface->addr[i] ) 
7686         goto Bad_CallBackRxConnAddr;
7687
7688     conn = rx_NewConnection (thost->interface->addr[i],
7689                              thost->port, 1, sc, 0);
7690     rx_SetConnDeadTime(conn, 2); 
7691     rx_SetConnHardDeadTime(conn, AFS_HARDDEADTIME); 
7692     H_UNLOCK;
7693     errorCode = RXAFSCB_Probe(conn);
7694     H_LOCK;
7695     if (!errorCode) {
7696         if ( thost->callback_rxcon )
7697             rx_DestroyConnection(thost->callback_rxcon);
7698         thost->callback_rxcon = conn;
7699         thost->host           = addr;
7700         rx_SetConnDeadTime(thost->callback_rxcon, 50);
7701         rx_SetConnHardDeadTime(thost->callback_rxcon, AFS_HARDDEADTIME);
7702         h_ReleaseClient_r(tclient);
7703         /* The hold on thost will be released by CallPostamble */
7704         H_UNLOCK;
7705         errorCode = CallPostamble(tcon, errorCode, tcallhost);
7706         return errorCode;
7707     } else {
7708         rx_DestroyConnection(conn);
7709     }       
7710   Bad_CallBackRxConnAddr:
7711     h_ReleaseClient_r(tclient);
7712     /* The hold on thost will be released by CallPostamble */
7713     H_UNLOCK;
7714 #endif
7715
7716     errorCode = CallPostamble(tcon, errorCode, tcallhost);
7717  Bad_CallBackRxConnAddr1:
7718     return errorCode;          /* failure */
7719 }
7720
7721 afs_int32
7722 sys_error_to_et(afs_int32 in)
7723 {
7724     if (in == 0)
7725         return 0;
7726     if (in < 0 || in > 511)
7727         return in;
7728     if ((in >= VICE_SPECIAL_ERRORS && in <= VIO) || in == VRESTRICTED)
7729         return in;
7730     if (sys2et[in] != 0)
7731         return sys2et[in];
7732     return in;
7733 }