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