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