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