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