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