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