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