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