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