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