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