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