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