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