DEVEL15-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), afs_inet_ntoa_r(rxr_HostOf(*tconn), hoststr2), 
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), afs_inet_ntoa_r(rxr_HostOf(*tconn), hoststr2), 
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     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2032 #if FS_STATS_DETAILED
2033     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2034     struct fs_stats_xferData *xferP;    /* Ptr to this op's byte size struct */
2035     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2036     struct timeval xferStartTime, xferStopTime; /* Start/stop times for xfer portion */
2037     struct timeval elapsedTime; /* Transfer time */
2038     afs_sfsize_t bytesToXfer;   /* # bytes to xfer */
2039     afs_sfsize_t bytesXferred;  /* # bytes actually xferred */
2040     int readIdx;                /* Index of read stats array to bump */
2041     static afs_int32 tot_bytesXferred;  /* shared access protected by FS_LOCK */
2042
2043     /*
2044      * Set our stats pointers, remember when the RPC operation started, and
2045      * tally the operation.
2046      */
2047     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHDATA]);
2048     xferP = &(afs_FullPerfStats.det.xferOpTimes[FS_STATS_XFERIDX_FETCHDATA]);
2049     FS_LOCK;
2050     (opP->numOps)++;
2051     FS_UNLOCK;
2052     TM_GetTimeOfDay(&opStartTime, 0);
2053 #endif /* FS_STATS_DETAILED */
2054
2055     ViceLog(1,
2056             ("SRXAFS_FetchData, Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2057              Fid->Unique));
2058     FS_LOCK;
2059     AFSCallStats.FetchData++, AFSCallStats.TotalCalls++;
2060     FS_UNLOCK;
2061     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2062         goto Bad_FetchData;
2063
2064     /* Get ptr to client data for user Id for logging */
2065     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2066     logHostAddr.s_addr = rxr_HostOf(tcon);
2067     ViceLog(5,
2068             ("SRXAFS_FetchData, Fid = %u.%u.%u, Host %s:%d, Id %d\n",
2069              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2070              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2071     /*
2072      * Get volume/vnode for the fetched file; caller's access rights to
2073      * it are also returned
2074      */
2075     if ((errorCode =
2076          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
2077                           &parentwhentargetnotdir, &client, READ_LOCK,
2078                           &rights, &anyrights)))
2079         goto Bad_FetchData;
2080
2081     SetVolumeSync(Sync, volptr);
2082
2083 #if FS_STATS_DETAILED
2084     /*
2085      * Remember that another read operation was performed.
2086      */
2087     FS_LOCK;
2088     if (client->InSameNetwork)
2089         readIdx = VOL_STATS_SAME_NET;
2090     else
2091         readIdx = VOL_STATS_DIFF_NET;
2092     V_stat_reads(volptr, readIdx)++;
2093     if (client->ViceId != AnonymousID) {
2094         V_stat_reads(volptr, readIdx + 1)++;
2095     }
2096     FS_UNLOCK;
2097 #endif /* FS_STATS_DETAILED */
2098     /* Check whether the caller has permission access to fetch the data */
2099     if ((errorCode =
2100          Check_PermissionRights(targetptr, client, rights, CHK_FETCHDATA, 0)))
2101         goto Bad_FetchData;
2102
2103     /*
2104      * Drop the read lock on the parent directory after saving the parent
2105      * vnode information we need to pass to GetStatus
2106      */
2107     if (parentwhentargetnotdir != NULL) {
2108         tparentwhentargetnotdir = *parentwhentargetnotdir;
2109         VPutVnode(&fileCode, parentwhentargetnotdir);
2110         assert(!fileCode || (fileCode == VSALVAGE));
2111         parentwhentargetnotdir = NULL;
2112     }
2113 #if FS_STATS_DETAILED
2114     /*
2115      * Remember when the data transfer started.
2116      */
2117     TM_GetTimeOfDay(&xferStartTime, 0);
2118 #endif /* FS_STATS_DETAILED */
2119
2120     /* actually do the data transfer */
2121 #if FS_STATS_DETAILED
2122     errorCode =
2123         FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type,
2124                           &bytesToXfer, &bytesXferred);
2125 #else
2126     if ((errorCode =
2127          FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type)))
2128         goto Bad_FetchData;
2129 #endif /* FS_STATS_DETAILED */
2130
2131 #if FS_STATS_DETAILED
2132     /*
2133      * At this point, the data transfer is done, for good or ill.  Remember
2134      * when the transfer ended, bump the number of successes/failures, and
2135      * integrate the transfer size and elapsed time into the stats.  If the
2136      * operation failed, we jump to the appropriate point.
2137      */
2138     TM_GetTimeOfDay(&xferStopTime, 0);
2139     FS_LOCK;
2140     (xferP->numXfers)++;
2141     if (!errorCode) {
2142         (xferP->numSuccesses)++;
2143
2144         /*
2145          * Bump the xfer sum by the number of bytes actually sent, NOT the
2146          * target number.
2147          */
2148         tot_bytesXferred += bytesXferred;
2149         (xferP->sumBytes) += (tot_bytesXferred >> 10);
2150         tot_bytesXferred &= 0x3FF;
2151         if (bytesXferred < xferP->minBytes)
2152             xferP->minBytes = bytesXferred;
2153         if (bytesXferred > xferP->maxBytes)
2154             xferP->maxBytes = bytesXferred;
2155
2156         /*
2157          * Tally the size of the object.  Note: we tally the actual size,
2158          * NOT the number of bytes that made it out over the wire.
2159          */
2160         if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET0)
2161             (xferP->count[0])++;
2162         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET1)
2163             (xferP->count[1])++;
2164         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET2)
2165             (xferP->count[2])++;
2166         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET3)
2167             (xferP->count[3])++;
2168         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET4)
2169             (xferP->count[4])++;
2170         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET5)
2171             (xferP->count[5])++;
2172         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET6)
2173             (xferP->count[6])++;
2174         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET7)
2175             (xferP->count[7])++;
2176         else
2177             (xferP->count[8])++;
2178
2179         fs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
2180         fs_stats_AddTo((xferP->sumTime), elapsedTime);
2181         fs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
2182         if (fs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
2183             fs_stats_TimeAssign((xferP->minTime), elapsedTime);
2184         }
2185         if (fs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
2186             fs_stats_TimeAssign((xferP->maxTime), elapsedTime);
2187         }
2188     }
2189     FS_UNLOCK;
2190     /*
2191      * Finally, go off to tell our caller the bad news in case the
2192      * fetch failed.
2193      */
2194     if (errorCode)
2195         goto Bad_FetchData;
2196 #endif /* FS_STATS_DETAILED */
2197
2198     /* write back  the OutStatus from the target vnode  */
2199     GetStatus(targetptr, OutStatus, rights, anyrights,
2200               &tparentwhentargetnotdir);
2201
2202     /* if a r/w volume, promise a callback to the caller */
2203     if (VolumeWriteable(volptr))
2204         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2205     else {
2206         struct AFSFid myFid;
2207         memset(&myFid, 0, sizeof(struct AFSFid));
2208         myFid.Volume = Fid->Volume;
2209         SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2210     }
2211
2212   Bad_FetchData:
2213     /* Update and store volume/vnode and parent vnodes back */
2214     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2215                            volptr, &client);
2216     ViceLog(2, ("SRXAFS_FetchData returns %d\n", errorCode));
2217     errorCode = CallPostamble(tcon, errorCode, thost);
2218
2219 #if FS_STATS_DETAILED
2220     TM_GetTimeOfDay(&opStopTime, 0);
2221     if (errorCode == 0) {
2222         FS_LOCK;
2223         (opP->numSuccesses)++;
2224         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2225         fs_stats_AddTo((opP->sumTime), elapsedTime);
2226         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2227         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2228             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2229         }
2230         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2231             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2232         }
2233         FS_UNLOCK;
2234     }
2235 #endif /* FS_STATS_DETAILED */
2236
2237     osi_auditU(acall, FetchDataEvent, errorCode, 
2238                AUD_ID, t_client ? t_client->ViceId : 0,
2239                AUD_FID, Fid, AUD_END);
2240     return (errorCode);
2241
2242 }                               /*SRXAFS_FetchData */
2243
2244 afs_int32
2245 SRXAFS_FetchData(struct rx_call * acall, struct AFSFid * Fid, afs_int32 Pos,
2246                  afs_int32 Len, struct AFSFetchStatus * OutStatus,
2247                  struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2248 {
2249     return common_FetchData64(acall, Fid, Pos, Len, OutStatus, CallBack, 
2250                               Sync, 0);
2251 }
2252
2253 afs_int32
2254 SRXAFS_FetchData64(struct rx_call * acall, struct AFSFid * Fid, afs_int64 Pos,
2255                    afs_int64 Len, struct AFSFetchStatus * OutStatus,
2256                    struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2257 {
2258     int code;
2259     afs_sfsize_t tPos, tLen;
2260
2261 #ifdef AFS_64BIT_ENV
2262 #ifndef AFS_LARGEFILE_ENV
2263     if (Pos + Len > 0x7fffffff)
2264         return EFBIG;
2265 #endif /* !AFS_LARGEFILE_ENV */
2266     tPos = (afs_sfsize_t) Pos;
2267     tLen = (afs_sfsize_t) Len;
2268 #else /* AFS_64BIT_ENV */
2269     if (Pos.high || Len.high)
2270         return EFBIG;
2271     tPos = Pos.low;
2272     tLen = Len.low;
2273 #endif /* AFS_64BIT_ENV */
2274
2275     code =
2276         common_FetchData64(acall, Fid, tPos, tLen, OutStatus, CallBack, Sync,
2277                            1);
2278     return code;
2279 }
2280
2281 afs_int32
2282 SRXAFS_FetchACL(struct rx_call * acall, struct AFSFid * Fid,
2283                 struct AFSOpaque * AccessList,
2284                 struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
2285 {
2286     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2287     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2288     int errorCode = 0;          /* return error code to caller */
2289     Volume *volptr = 0;         /* pointer to the volume */
2290     struct client *client = 0;  /* pointer to the client data */
2291     afs_int32 rights, anyrights;        /* rights for this and any user */
2292     struct rx_connection *tcon = rx_ConnectionOf(acall);
2293     struct host *thost;
2294     struct client *t_client = NULL;     /* tmp ptr to client data */
2295     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2296 #if FS_STATS_DETAILED
2297     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2298     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2299     struct timeval elapsedTime; /* Transfer time */
2300
2301     /*
2302      * Set our stats pointer, remember when the RPC operation started, and
2303      * tally the operation.
2304      */
2305     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHACL]);
2306     FS_LOCK;
2307     (opP->numOps)++;
2308     FS_UNLOCK;
2309     TM_GetTimeOfDay(&opStartTime, 0);
2310 #endif /* FS_STATS_DETAILED */
2311
2312     ViceLog(1,
2313             ("SAFS_FetchACL, Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2314              Fid->Unique));
2315     FS_LOCK;
2316     AFSCallStats.FetchACL++, AFSCallStats.TotalCalls++;
2317     FS_UNLOCK;
2318     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2319         goto Bad_FetchACL;
2320
2321     /* Get ptr to client data for user Id for logging */
2322     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2323     logHostAddr.s_addr = rxr_HostOf(tcon);
2324     ViceLog(5,
2325             ("SAFS_FetchACL, Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
2326              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2327              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2328
2329     AccessList->AFSOpaque_len = 0;
2330     AccessList->AFSOpaque_val = malloc(AFSOPAQUEMAX);
2331     if (!AccessList->AFSOpaque_val) {
2332         ViceLog(0, ("Failed malloc in SRXAFS_FetchACL\n"));
2333         assert(0);
2334     }
2335
2336     /*
2337      * Get volume/vnode for the fetched file; caller's access rights to it
2338      * are also returned
2339      */
2340     if ((errorCode =
2341          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
2342                           &parentwhentargetnotdir, &client, READ_LOCK,
2343                           &rights, &anyrights)))
2344         goto Bad_FetchACL;
2345
2346     SetVolumeSync(Sync, volptr);
2347
2348     /* Check whether we have permission to fetch the ACL */
2349     if ((errorCode =
2350          Check_PermissionRights(targetptr, client, rights, CHK_FETCHACL, 0)))
2351         goto Bad_FetchACL;
2352
2353     /* Get the Access List from the dir's vnode */
2354     if ((errorCode =
2355          RXFetch_AccessList(targetptr, parentwhentargetnotdir, AccessList)))
2356         goto Bad_FetchACL;
2357
2358     /* Get OutStatus back From the target Vnode  */
2359     GetStatus(targetptr, OutStatus, rights, anyrights,
2360               parentwhentargetnotdir);
2361
2362   Bad_FetchACL:
2363     /* Update and store volume/vnode and parent vnodes back */
2364     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2365                            volptr, &client);
2366     ViceLog(2,
2367             ("SAFS_FetchACL returns %d (ACL=%s)\n", errorCode,
2368              AccessList->AFSOpaque_val));
2369     errorCode = CallPostamble(tcon, errorCode, thost);
2370
2371 #if FS_STATS_DETAILED
2372     TM_GetTimeOfDay(&opStopTime, 0);
2373     if (errorCode == 0) {
2374         FS_LOCK;
2375         (opP->numSuccesses)++;
2376         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2377         fs_stats_AddTo((opP->sumTime), elapsedTime);
2378         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2379         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2380             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2381         }
2382         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2383             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2384         }
2385         FS_UNLOCK;
2386     }
2387 #endif /* FS_STATS_DETAILED */
2388
2389     osi_auditU(acall, FetchACLEvent, errorCode, 
2390                AUD_ID, t_client ? t_client->ViceId : 0,
2391                AUD_FID, Fid, 
2392                AUD_ACL, AccessList->AFSOpaque_val, AUD_END);
2393     return errorCode;
2394 }                               /*SRXAFS_FetchACL */
2395
2396
2397 /*
2398  * This routine is called exclusively by SRXAFS_FetchStatus(), and should be
2399  * merged into it when possible.
2400  */
2401 static
2402   afs_int32
2403 SAFSS_FetchStatus(struct rx_call *acall, struct AFSFid *Fid,
2404                   struct AFSFetchStatus *OutStatus,
2405                   struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
2406 {
2407     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2408     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2409     int errorCode = 0;          /* return code to caller */
2410     Volume *volptr = 0;         /* pointer to the volume */
2411     struct client *client = 0;  /* pointer to the client data */
2412     afs_int32 rights, anyrights;        /* rights for this and any user */
2413     struct client *t_client = NULL;     /* tmp ptr to client data */
2414     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2415     struct rx_connection *tcon = rx_ConnectionOf(acall);
2416
2417     /* Get ptr to client data for user Id for logging */
2418     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2419     logHostAddr.s_addr = rxr_HostOf(tcon);
2420     ViceLog(1,
2421             ("SAFS_FetchStatus,  Fid = %u.%u.%u, Host %s:%d, Id %d\n",
2422              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2423              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2424     FS_LOCK;
2425     AFSCallStats.FetchStatus++, AFSCallStats.TotalCalls++;
2426     FS_UNLOCK;
2427     /*
2428      * Get volume/vnode for the fetched file; caller's rights to it are
2429      * also returned
2430      */
2431     if ((errorCode =
2432          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
2433                           &parentwhentargetnotdir, &client, READ_LOCK,
2434                           &rights, &anyrights)))
2435         goto Bad_FetchStatus;
2436
2437     /* set volume synchronization information */
2438     SetVolumeSync(Sync, volptr);
2439
2440     /* Are we allowed to fetch Fid's status? */
2441     if (targetptr->disk.type != vDirectory) {
2442         if ((errorCode =
2443              Check_PermissionRights(targetptr, client, rights,
2444                                     CHK_FETCHSTATUS, 0))) {
2445             if (rx_GetCallAbortCode(acall) == errorCode)
2446                 rx_SetCallAbortCode(acall, 0);
2447             goto Bad_FetchStatus;
2448         }
2449     }
2450
2451     /* set OutStatus From the Fid  */
2452     GetStatus(targetptr, OutStatus, rights, anyrights,
2453               parentwhentargetnotdir);
2454
2455     /* If a r/w volume, also set the CallBack state */
2456     if (VolumeWriteable(volptr))
2457         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2458     else {
2459         struct AFSFid myFid;
2460         memset(&myFid, 0, sizeof(struct AFSFid));
2461         myFid.Volume = Fid->Volume;
2462         SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2463     }
2464
2465   Bad_FetchStatus:
2466     /* Update and store volume/vnode and parent vnodes back */
2467     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2468                            volptr, &client);
2469     ViceLog(2, ("SAFS_FetchStatus returns %d\n", errorCode));
2470     return errorCode;
2471
2472 }                               /*SAFSS_FetchStatus */
2473
2474
2475 afs_int32
2476 SRXAFS_BulkStatus(struct rx_call * acall, struct AFSCBFids * Fids,
2477                   struct AFSBulkStats * OutStats, struct AFSCBs * CallBacks,
2478                   struct AFSVolSync * Sync)
2479 {
2480     register int i;
2481     afs_int32 nfiles;
2482     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2483     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2484     int errorCode = 0;          /* return code to caller */
2485     Volume *volptr = 0;         /* pointer to the volume */
2486     struct client *client = 0;  /* pointer to the client data */
2487     afs_int32 rights, anyrights;        /* rights for this and any user */
2488     register struct AFSFid *tfid;       /* file id we're dealing with now */
2489     struct rx_connection *tcon = rx_ConnectionOf(acall);
2490     struct host *thost;
2491     struct client *t_client = NULL;     /* tmp pointer to the client data */
2492 #if FS_STATS_DETAILED
2493     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2494     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2495     struct timeval elapsedTime; /* Transfer time */
2496
2497     /*
2498      * Set our stats pointer, remember when the RPC operation started, and
2499      * tally the operation.
2500      */
2501     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_BULKSTATUS]);
2502     FS_LOCK;
2503     (opP->numOps)++;
2504     FS_UNLOCK;
2505     TM_GetTimeOfDay(&opStartTime, 0);
2506 #endif /* FS_STATS_DETAILED */
2507
2508     ViceLog(1, ("SAFS_BulkStatus\n"));
2509     FS_LOCK;
2510     AFSCallStats.TotalCalls++;
2511     FS_UNLOCK;
2512     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2513     if (nfiles <= 0) {          /* Sanity check */
2514         errorCode = EINVAL;
2515         goto Audit_and_Return;
2516     }
2517
2518     /* allocate space for return output parameters */
2519     OutStats->AFSBulkStats_val = (struct AFSFetchStatus *)
2520         malloc(nfiles * sizeof(struct AFSFetchStatus));
2521     if (!OutStats->AFSBulkStats_val) {
2522         ViceLog(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2523         assert(0);
2524     }
2525     OutStats->AFSBulkStats_len = nfiles;
2526     CallBacks->AFSCBs_val = (struct AFSCallBack *)
2527         malloc(nfiles * sizeof(struct AFSCallBack));
2528     if (!CallBacks->AFSCBs_val) {
2529         ViceLog(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2530         assert(0);
2531     }
2532     CallBacks->AFSCBs_len = nfiles;
2533
2534     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2535         goto Bad_BulkStatus;
2536
2537     tfid = Fids->AFSCBFids_val;
2538     for (i = 0; i < nfiles; i++, tfid++) {
2539         /*
2540          * Get volume/vnode for the fetched file; caller's rights to it
2541          * are also returned
2542          */
2543         if ((errorCode =
2544              GetVolumePackage(tcon, tfid, &volptr, &targetptr, DONTCHECK,
2545                               &parentwhentargetnotdir, &client, READ_LOCK,
2546                               &rights, &anyrights)))
2547             goto Bad_BulkStatus;
2548         /* set volume synchronization information, but only once per call */
2549         if (i == nfiles)
2550             SetVolumeSync(Sync, volptr);
2551
2552         /* Are we allowed to fetch Fid's status? */
2553         if (targetptr->disk.type != vDirectory) {
2554             if ((errorCode =
2555                  Check_PermissionRights(targetptr, client, rights,
2556                                         CHK_FETCHSTATUS, 0))) {
2557                 if (rx_GetCallAbortCode(acall) == errorCode)
2558                     rx_SetCallAbortCode(acall, 0);
2559                 goto Bad_BulkStatus;
2560             }
2561         }
2562
2563         /* set OutStatus From the Fid  */
2564         GetStatus(targetptr, &OutStats->AFSBulkStats_val[i], rights,
2565                   anyrights, parentwhentargetnotdir);
2566
2567         /* If a r/w volume, also set the CallBack state */
2568         if (VolumeWriteable(volptr))
2569             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2570                               &CallBacks->AFSCBs_val[i]);
2571         else {
2572             struct AFSFid myFid;
2573             memset(&myFid, 0, sizeof(struct AFSFid));
2574             myFid.Volume = tfid->Volume;
2575             SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2576                               &CallBacks->AFSCBs_val[i]);
2577         }
2578
2579         /* put back the file ID and volume */
2580         (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2581                                volptr, &client);
2582         parentwhentargetnotdir = (Vnode *) 0;
2583         targetptr = (Vnode *) 0;
2584         volptr = (Volume *) 0;
2585         client = (struct client *)0;
2586     }
2587
2588   Bad_BulkStatus:
2589     /* Update and store volume/vnode and parent vnodes back */
2590     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2591                            volptr, &client);
2592     errorCode = CallPostamble(tcon, errorCode, thost);
2593
2594     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2595
2596 #if FS_STATS_DETAILED
2597     TM_GetTimeOfDay(&opStopTime, 0);
2598     if (errorCode == 0) {
2599         FS_LOCK;
2600         (opP->numSuccesses)++;
2601         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2602         fs_stats_AddTo((opP->sumTime), elapsedTime);
2603         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2604         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2605             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2606         }
2607         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2608             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2609         }
2610         FS_UNLOCK;
2611     }
2612 #endif /* FS_STATS_DETAILED */
2613
2614   Audit_and_Return:
2615     ViceLog(2, ("SAFS_BulkStatus        returns %d\n", errorCode));
2616     osi_auditU(acall, BulkFetchStatusEvent, errorCode, 
2617                AUD_ID, t_client ? t_client->ViceId : 0,
2618                AUD_FIDS, Fids, AUD_END);
2619     return errorCode;
2620
2621 }                               /*SRXAFS_BulkStatus */
2622
2623
2624 afs_int32
2625 SRXAFS_InlineBulkStatus(struct rx_call * acall, struct AFSCBFids * Fids,
2626                         struct AFSBulkStats * OutStats,
2627                         struct AFSCBs * CallBacks, struct AFSVolSync * Sync)
2628 {
2629     register int i;
2630     afs_int32 nfiles;
2631     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2632     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2633     int errorCode = 0;          /* return code to caller */
2634     Volume *volptr = 0;         /* pointer to the volume */
2635     struct client *client = 0;  /* pointer to the client data */
2636     afs_int32 rights, anyrights;        /* rights for this and any user */
2637     register struct AFSFid *tfid;       /* file id we're dealing with now */
2638     struct rx_connection *tcon;
2639     struct host *thost;
2640     struct client *t_client = NULL;     /* tmp ptr to client data */
2641     AFSFetchStatus *tstatus;
2642 #if FS_STATS_DETAILED
2643     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2644     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2645     struct timeval elapsedTime; /* Transfer time */
2646
2647     /*
2648      * Set our stats pointer, remember when the RPC operation started, and
2649      * tally the operation.
2650      */
2651     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_BULKSTATUS]);
2652     FS_LOCK;
2653     (opP->numOps)++;
2654     FS_UNLOCK;
2655     TM_GetTimeOfDay(&opStartTime, 0);
2656 #endif /* FS_STATS_DETAILED */
2657
2658     ViceLog(1, ("SAFS_InlineBulkStatus\n"));
2659     FS_LOCK;
2660     AFSCallStats.TotalCalls++;
2661     FS_UNLOCK;
2662     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2663     if (nfiles <= 0) {          /* Sanity check */
2664         errorCode = EINVAL;
2665         goto Audit_and_Return;
2666     }
2667
2668     /* allocate space for return output parameters */
2669     OutStats->AFSBulkStats_val = (struct AFSFetchStatus *)
2670         malloc(nfiles * sizeof(struct AFSFetchStatus));
2671     if (!OutStats->AFSBulkStats_val) {
2672         ViceLog(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2673         assert(0);
2674     }
2675     OutStats->AFSBulkStats_len = nfiles;
2676     CallBacks->AFSCBs_val = (struct AFSCallBack *)
2677         malloc(nfiles * sizeof(struct AFSCallBack));
2678     if (!CallBacks->AFSCBs_val) {
2679         ViceLog(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2680         assert(0);
2681     }
2682     CallBacks->AFSCBs_len = nfiles;
2683
2684     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost))) {
2685         goto Bad_InlineBulkStatus;
2686     }
2687
2688     tfid = Fids->AFSCBFids_val;
2689     for (i = 0; i < nfiles; i++, tfid++) {
2690         /*
2691          * Get volume/vnode for the fetched file; caller's rights to it
2692          * are also returned
2693          */
2694         if ((errorCode =
2695              GetVolumePackage(tcon, tfid, &volptr, &targetptr, DONTCHECK,
2696                               &parentwhentargetnotdir, &client, READ_LOCK,
2697                               &rights, &anyrights))) {
2698             tstatus = &OutStats->AFSBulkStats_val[i];
2699             tstatus->errorCode = errorCode;
2700             PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
2701                              volptr, &client);
2702             parentwhentargetnotdir = (Vnode *) 0;
2703             targetptr = (Vnode *) 0;
2704             volptr = (Volume *) 0;
2705             client = (struct client *)0;
2706             continue;
2707         }
2708
2709         /* set volume synchronization information, but only once per call */
2710         if (i == nfiles)
2711             SetVolumeSync(Sync, volptr);
2712
2713         /* Are we allowed to fetch Fid's status? */
2714         if (targetptr->disk.type != vDirectory) {
2715             if ((errorCode =
2716                  Check_PermissionRights(targetptr, client, rights,
2717                                         CHK_FETCHSTATUS, 0))) {
2718                 tstatus = &OutStats->AFSBulkStats_val[i];
2719                 tstatus->errorCode = errorCode;
2720                 (void)PutVolumePackage(parentwhentargetnotdir, targetptr,
2721                                        (Vnode *) 0, volptr, &client);
2722                 parentwhentargetnotdir = (Vnode *) 0;
2723                 targetptr = (Vnode *) 0;
2724                 volptr = (Volume *) 0;
2725                 client = (struct client *)0;
2726                 continue;
2727             }
2728         }
2729
2730         /* set OutStatus From the Fid  */
2731         GetStatus(targetptr,
2732                   (struct AFSFetchStatus *)&OutStats->AFSBulkStats_val[i],
2733                   rights, anyrights, parentwhentargetnotdir);
2734
2735         /* If a r/w volume, also set the CallBack state */
2736         if (VolumeWriteable(volptr))
2737             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2738                               &CallBacks->AFSCBs_val[i]);
2739         else {
2740             struct AFSFid myFid;
2741             memset(&myFid, 0, sizeof(struct AFSFid));
2742             myFid.Volume = tfid->Volume;
2743             SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2744                               &CallBacks->AFSCBs_val[i]);
2745         }
2746
2747         /* put back the file ID and volume */
2748         (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2749                                volptr, &client);
2750         parentwhentargetnotdir = (Vnode *) 0;
2751         targetptr = (Vnode *) 0;
2752         volptr = (Volume *) 0;
2753         client = (struct client *)0;
2754     }
2755
2756   Bad_InlineBulkStatus:
2757     /* Update and store volume/vnode and parent vnodes back */
2758     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2759                            volptr, &client);
2760     errorCode = CallPostamble(tcon, errorCode, thost);
2761
2762     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2763
2764 #if FS_STATS_DETAILED
2765     TM_GetTimeOfDay(&opStopTime, 0);
2766     if (errorCode == 0) {
2767         FS_LOCK;
2768         (opP->numSuccesses)++;
2769         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2770         fs_stats_AddTo((opP->sumTime), elapsedTime);
2771         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2772         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2773             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2774         }
2775         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2776             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2777         }
2778         FS_UNLOCK;
2779     }
2780 #endif /* FS_STATS_DETAILED */
2781
2782   Audit_and_Return:
2783     ViceLog(2, ("SAFS_InlineBulkStatus  returns %d\n", errorCode));
2784     osi_auditU(acall, InlineBulkFetchStatusEvent, errorCode, 
2785                AUD_ID, t_client ? t_client->ViceId : 0,
2786                AUD_FIDS, Fids, AUD_END);
2787     return 0;
2788
2789 }                               /*SRXAFS_InlineBulkStatus */
2790
2791
2792 afs_int32
2793 SRXAFS_FetchStatus(struct rx_call * acall, struct AFSFid * Fid,
2794                    struct AFSFetchStatus * OutStatus,
2795                    struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2796 {
2797     afs_int32 code;
2798     struct rx_connection *tcon;
2799     struct host *thost;
2800     struct client *t_client = NULL;     /* tmp ptr to client data */
2801 #if FS_STATS_DETAILED
2802     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2803     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2804     struct timeval elapsedTime; /* Transfer time */
2805
2806     /*
2807      * Set our stats pointer, remember when the RPC operation started, and
2808      * tally the operation.
2809      */
2810     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHSTATUS]);
2811     FS_LOCK;
2812     (opP->numOps)++;
2813     FS_UNLOCK;
2814     TM_GetTimeOfDay(&opStartTime, 0);
2815 #endif /* FS_STATS_DETAILED */
2816
2817     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2818         goto Bad_FetchStatus;
2819
2820     code = SAFSS_FetchStatus(acall, Fid, OutStatus, CallBack, Sync);
2821
2822   Bad_FetchStatus:
2823     code = CallPostamble(tcon, code, thost);
2824
2825     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2826
2827 #if FS_STATS_DETAILED
2828     TM_GetTimeOfDay(&opStopTime, 0);
2829     if (code == 0) {
2830         FS_LOCK;
2831         (opP->numSuccesses)++;
2832         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2833         fs_stats_AddTo((opP->sumTime), elapsedTime);
2834         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2835         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2836             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2837         }
2838         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2839             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2840         }
2841         FS_UNLOCK;
2842     }
2843 #endif /* FS_STATS_DETAILED */
2844
2845     osi_auditU(acall, FetchStatusEvent, code, 
2846                AUD_ID, t_client ? t_client->ViceId : 0,
2847                AUD_FID, Fid, AUD_END);
2848     return code;
2849
2850 }                               /*SRXAFS_FetchStatus */
2851
2852 static
2853   afs_int32
2854 common_StoreData64(struct rx_call *acall, struct AFSFid *Fid,
2855                    struct AFSStoreStatus *InStatus, afs_fsize_t Pos,
2856                    afs_fsize_t Length, afs_fsize_t FileLength,
2857                    struct AFSFetchStatus *OutStatus, struct AFSVolSync *Sync)
2858 {
2859     Vnode *targetptr = 0;       /* pointer to input fid */
2860     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
2861     Vnode tparentwhentargetnotdir;      /* parent vnode for GetStatus */
2862     int errorCode = 0;          /* return code for caller */
2863     int fileCode = 0;           /* return code from vol package */
2864     Volume *volptr = 0;         /* pointer to the volume header */
2865     struct client *client = 0;  /* pointer to client structure */
2866     afs_int32 rights, anyrights;        /* rights for this and any user */
2867     struct client *t_client = NULL;     /* tmp ptr to client data */
2868     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2869     struct rx_connection *tcon;
2870     struct host *thost;
2871 #if FS_STATS_DETAILED
2872     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2873     struct fs_stats_xferData *xferP;    /* Ptr to this op's byte size struct */
2874     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2875     struct timeval xferStartTime, xferStopTime; /* Start/stop times for xfer portion */
2876     struct timeval elapsedTime; /* Transfer time */
2877     afs_sfsize_t bytesToXfer;   /* # bytes to xfer */
2878     afs_sfsize_t bytesXferred;  /* # bytes actually xfer */
2879     static afs_int32 tot_bytesXferred;  /* shared access protected by FS_LOCK */
2880
2881     /*
2882      * Set our stats pointers, remember when the RPC operation started, and
2883      * tally the operation.
2884      */
2885     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STOREDATA]);
2886     xferP = &(afs_FullPerfStats.det.xferOpTimes[FS_STATS_XFERIDX_STOREDATA]);
2887     FS_LOCK;
2888     (opP->numOps)++;
2889     FS_UNLOCK;
2890     ViceLog(1,
2891             ("StoreData: Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2892              Fid->Unique));
2893     TM_GetTimeOfDay(&opStartTime, 0);
2894 #endif /* FS_STATS_DETAILED */
2895
2896     FS_LOCK;
2897     AFSCallStats.StoreData++, AFSCallStats.TotalCalls++;
2898     FS_UNLOCK;
2899     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2900         goto Bad_StoreData;
2901
2902     /* Get ptr to client data for user Id for logging */
2903     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2904     logHostAddr.s_addr = rxr_HostOf(tcon);
2905     ViceLog(5,
2906             ("StoreData: Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
2907              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2908              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2909
2910     /*
2911      * Get associated volume/vnode for the stored file; caller's rights
2912      * are also returned
2913      */
2914     if ((errorCode =
2915          GetVolumePackage(tcon, Fid, &volptr, &targetptr, MustNOTBeDIR,
2916                           &parentwhentargetnotdir, &client, WRITE_LOCK,
2917                           &rights, &anyrights))) {
2918         goto Bad_StoreData;
2919     }
2920
2921     /* set volume synchronization information */
2922     SetVolumeSync(Sync, volptr);
2923
2924     if ((targetptr->disk.type == vSymlink)) {
2925         /* Should we return a better error code here??? */
2926         errorCode = EISDIR;
2927         goto Bad_StoreData;
2928     }
2929
2930     /* Check if we're allowed to store the data */
2931     if ((errorCode =
2932          Check_PermissionRights(targetptr, client, rights, CHK_STOREDATA,
2933                                 InStatus))) {
2934         goto Bad_StoreData;
2935     }
2936
2937     /*
2938      * Drop the read lock on the parent directory after saving the parent
2939      * vnode information we need to pass to GetStatus
2940      */
2941     if (parentwhentargetnotdir != NULL) {
2942         tparentwhentargetnotdir = *parentwhentargetnotdir;
2943         VPutVnode(&fileCode, parentwhentargetnotdir);
2944         assert(!fileCode || (fileCode == VSALVAGE));
2945         parentwhentargetnotdir = NULL;
2946     }
2947 #if FS_STATS_DETAILED
2948     /*
2949      * Remember when the data transfer started.
2950      */
2951     TM_GetTimeOfDay(&xferStartTime, 0);
2952 #endif /* FS_STATS_DETAILED */
2953
2954     /* Do the actual storing of the data */
2955 #if FS_STATS_DETAILED
2956     errorCode =
2957         StoreData_RXStyle(volptr, targetptr, Fid, client, acall, Pos, Length,
2958                           FileLength, (InStatus->Mask & AFS_FSYNC),
2959                           &bytesToXfer, &bytesXferred);
2960 #else
2961     errorCode =
2962         StoreData_RXStyle(volptr, targetptr, Fid, client, acall, Pos, Length,
2963                           FileLength, (InStatus->Mask & AFS_FSYNC));
2964     if (errorCode && (!targetptr->changed_newTime))
2965         goto Bad_StoreData;
2966 #endif /* FS_STATS_DETAILED */
2967 #if FS_STATS_DETAILED
2968     /*
2969      * At this point, the data transfer is done, for good or ill.  Remember
2970      * when the transfer ended, bump the number of successes/failures, and
2971      * integrate the transfer size and elapsed time into the stats.  If the
2972      * operation failed, we jump to the appropriate point.
2973      */
2974     TM_GetTimeOfDay(&xferStopTime, 0);
2975     FS_LOCK;
2976     (xferP->numXfers)++;
2977     if (!errorCode) {
2978         (xferP->numSuccesses)++;
2979
2980         /*
2981          * Bump the xfer sum by the number of bytes actually sent, NOT the
2982          * target number.
2983          */
2984         tot_bytesXferred += bytesXferred;
2985         (xferP->sumBytes) += (tot_bytesXferred >> 10);
2986         tot_bytesXferred &= 0x3FF;
2987         if (bytesXferred < xferP->minBytes)
2988             xferP->minBytes = bytesXferred;
2989         if (bytesXferred > xferP->maxBytes)
2990             xferP->maxBytes = bytesXferred;
2991
2992         /*
2993          * Tally the size of the object.  Note: we tally the actual size,
2994          * NOT the number of bytes that made it out over the wire.
2995          */
2996         if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET0)
2997             (xferP->count[0])++;
2998         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET1)
2999             (xferP->count[1])++;
3000         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET2)
3001             (xferP->count[2])++;
3002         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET3)
3003             (xferP->count[3])++;
3004         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET4)
3005             (xferP->count[4])++;
3006         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET5)
3007             (xferP->count[5])++;
3008         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET6)
3009             (xferP->count[6])++;
3010         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET7)
3011             (xferP->count[7])++;
3012         else
3013             (xferP->count[8])++;
3014
3015         fs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
3016         fs_stats_AddTo((xferP->sumTime), elapsedTime);
3017         fs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
3018         if (fs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
3019             fs_stats_TimeAssign((xferP->minTime), elapsedTime);
3020         }
3021         if (fs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
3022             fs_stats_TimeAssign((xferP->maxTime), elapsedTime);
3023         }
3024     }
3025     FS_UNLOCK;
3026     /*
3027      * Finally, go off to tell our caller the bad news in case the
3028      * store failed.
3029      */
3030     if (errorCode && (!targetptr->changed_newTime))
3031         goto Bad_StoreData;
3032 #endif /* FS_STATS_DETAILED */
3033
3034     /* Update the status of the target's vnode */
3035     Update_TargetVnodeStatus(targetptr, TVS_SDATA, client, InStatus,
3036                              targetptr, volptr, 0);
3037
3038     /* Get the updated File's status back to the caller */
3039     GetStatus(targetptr, OutStatus, rights, anyrights,
3040               &tparentwhentargetnotdir);
3041
3042   Bad_StoreData:
3043     /* Update and store volume/vnode and parent vnodes back */
3044     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
3045                            volptr, &client);
3046     ViceLog(2, ("SAFS_StoreData returns %d\n", errorCode));
3047
3048     errorCode = CallPostamble(tcon, errorCode, thost);
3049
3050 #if FS_STATS_DETAILED
3051     TM_GetTimeOfDay(&opStopTime, 0);
3052     if (errorCode == 0) {
3053         FS_LOCK;
3054         (opP->numSuccesses)++;
3055         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3056         fs_stats_AddTo((opP->sumTime), elapsedTime);
3057         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3058         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3059             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3060         }
3061         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3062             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3063         }
3064         FS_UNLOCK;
3065     }
3066 #endif /* FS_STATS_DETAILED */
3067     osi_auditU(acall, StoreDataEvent, errorCode, 
3068                AUD_ID, t_client ? t_client->ViceId : 0,
3069                AUD_FID, Fid, AUD_END);
3070     return (errorCode);
3071 }                               /*common_StoreData64 */
3072
3073 afs_int32
3074 SRXAFS_StoreData(struct rx_call * acall, struct AFSFid * Fid,
3075                  struct AFSStoreStatus * InStatus, afs_uint32 Pos,
3076                  afs_uint32 Length, afs_uint32 FileLength,
3077                  struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
3078 {
3079     if (FileLength > 0x7fffffff || Pos > 0x7fffffff || 
3080         (0x7fffffff - Pos) < Length)
3081         return EFBIG;
3082
3083     return common_StoreData64(acall, Fid, InStatus, Pos, Length, FileLength,
3084                               OutStatus, Sync);
3085 }                               /*SRXAFS_StoreData */
3086
3087 afs_int32
3088 SRXAFS_StoreData64(struct rx_call * acall, struct AFSFid * Fid,
3089                    struct AFSStoreStatus * InStatus, afs_uint64 Pos,
3090                    afs_uint64 Length, afs_uint64 FileLength,
3091                    struct AFSFetchStatus * OutStatus,
3092                    struct AFSVolSync * Sync)
3093 {
3094     int code;
3095     afs_fsize_t tPos;
3096     afs_fsize_t tLength;
3097     afs_fsize_t tFileLength;
3098
3099 #ifdef AFS_64BIT_ENV
3100 #ifndef AFS_LARGEFILE_ENV
3101     if (FileLength > 0x7fffffff)
3102         return EFBIG;
3103 #endif /* !AFS_LARGEFILE_ENV */
3104     tPos = (afs_fsize_t) Pos;
3105     tLength = (afs_fsize_t) Length;
3106     tFileLength = (afs_fsize_t) FileLength;
3107 #else /* AFS_64BIT_ENV */
3108     if (FileLength.high)
3109         return EFBIG;
3110     tPos = Pos.low;
3111     tLength = Length.low;
3112     tFileLength = FileLength.low;
3113 #endif /* AFS_64BIT_ENV */
3114
3115     code =
3116         common_StoreData64(acall, Fid, InStatus, tPos, tLength, tFileLength,
3117                            OutStatus, Sync);
3118     return code;
3119 }
3120
3121 afs_int32
3122 SRXAFS_StoreACL(struct rx_call * acall, struct AFSFid * Fid,
3123                 struct AFSOpaque * AccessList,
3124                 struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
3125 {
3126     Vnode *targetptr = 0;       /* pointer to input fid */
3127     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
3128     int errorCode = 0;          /* return code for caller */
3129     struct AFSStoreStatus InStatus;     /* Input status for fid */
3130     Volume *volptr = 0;         /* pointer to the volume header */
3131     struct client *client = 0;  /* pointer to client structure */
3132     afs_int32 rights, anyrights;        /* rights for this and any user */
3133     struct rx_connection *tcon;
3134     struct host *thost;
3135     struct client *t_client = NULL;     /* tmp ptr to client data */
3136     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3137 #if FS_STATS_DETAILED
3138     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3139     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3140     struct timeval elapsedTime; /* Transfer time */
3141
3142     /*
3143      * Set our stats pointer, remember when the RPC operation started, and
3144      * tally the operation.
3145      */
3146     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STOREACL]);
3147     FS_LOCK;
3148     (opP->numOps)++;
3149     FS_UNLOCK;
3150     TM_GetTimeOfDay(&opStartTime, 0);
3151 #endif /* FS_STATS_DETAILED */
3152     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3153         goto Bad_StoreACL;
3154
3155     /* Get ptr to client data for user Id for logging */
3156     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3157     logHostAddr.s_addr = rxr_HostOf(tcon);
3158     ViceLog(1,
3159             ("SAFS_StoreACL, Fid = %u.%u.%u, ACL=%s, Host %s:%d, Id %d\n",
3160              Fid->Volume, Fid->Vnode, Fid->Unique, AccessList->AFSOpaque_val,
3161              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3162     FS_LOCK;
3163     AFSCallStats.StoreACL++, AFSCallStats.TotalCalls++;
3164     FS_UNLOCK;
3165     InStatus.Mask = 0;          /* not storing any status */
3166
3167     /*
3168      * Get associated volume/vnode for the target dir; caller's rights
3169      * are also returned.
3170      */
3171     if ((errorCode =
3172          GetVolumePackage(tcon, Fid, &volptr, &targetptr, MustBeDIR,
3173                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3174                           &rights, &anyrights))) {
3175         goto Bad_StoreACL;
3176     }
3177
3178     /* set volume synchronization information */
3179     SetVolumeSync(Sync, volptr);
3180
3181     /* Check if we have permission to change the dir's ACL */
3182     if ((errorCode =
3183          Check_PermissionRights(targetptr, client, rights, CHK_STOREACL,
3184                                 &InStatus))) {
3185         goto Bad_StoreACL;
3186     }
3187
3188     /* Build and store the new Access List for the dir */
3189     if ((errorCode = RXStore_AccessList(targetptr, AccessList))) {
3190         goto Bad_StoreACL;
3191     }
3192
3193     targetptr->changed_newTime = 1;     /* status change of directory */
3194
3195     /* convert the write lock to a read lock before breaking callbacks */
3196     VVnodeWriteToRead(&errorCode, targetptr);
3197     assert(!errorCode || errorCode == VSALVAGE);
3198
3199     /* break call backs on the directory  */
3200     BreakCallBack(client->host, Fid, 0);
3201
3202     /* Get the updated dir's status back to the caller */
3203     GetStatus(targetptr, OutStatus, rights, anyrights, 0);
3204
3205   Bad_StoreACL:
3206     /* Update and store volume/vnode and parent vnodes back */
3207     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
3208                      volptr, &client);
3209     ViceLog(2, ("SAFS_StoreACL returns %d\n", errorCode));
3210     errorCode = CallPostamble(tcon, errorCode, thost);
3211
3212 #if FS_STATS_DETAILED
3213     TM_GetTimeOfDay(&opStopTime, 0);
3214     if (errorCode == 0) {
3215         FS_LOCK;
3216         (opP->numSuccesses)++;
3217         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3218         fs_stats_AddTo((opP->sumTime), elapsedTime);
3219         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3220         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3221             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3222         }
3223         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3224             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3225         }
3226         FS_UNLOCK;
3227     }
3228 #endif /* FS_STATS_DETAILED */
3229
3230     osi_auditU(acall, StoreACLEvent, errorCode, 
3231                AUD_ID, t_client ? t_client->ViceId : 0,
3232                AUD_FID, Fid, AUD_ACL, AccessList->AFSOpaque_val, AUD_END);
3233     return errorCode;
3234
3235 }                               /*SRXAFS_StoreACL */
3236
3237
3238 /*
3239  * Note: This routine is called exclusively from SRXAFS_StoreStatus(), and
3240  * should be merged when possible.
3241  */
3242 static afs_int32
3243 SAFSS_StoreStatus(struct rx_call *acall, struct AFSFid *Fid,
3244                   struct AFSStoreStatus *InStatus,
3245                   struct AFSFetchStatus *OutStatus, struct AFSVolSync *Sync)
3246 {
3247     Vnode *targetptr = 0;       /* pointer to input fid */
3248     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
3249     int errorCode = 0;          /* return code for caller */
3250     Volume *volptr = 0;         /* pointer to the volume header */
3251     struct client *client = 0;  /* pointer to client structure */
3252     afs_int32 rights, anyrights;        /* rights for this and any user */
3253     struct client *t_client = NULL;     /* tmp ptr to client data */
3254     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3255     struct rx_connection *tcon = rx_ConnectionOf(acall);
3256
3257     /* Get ptr to client data for user Id for logging */
3258     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3259     logHostAddr.s_addr = rxr_HostOf(tcon);
3260     ViceLog(1,
3261             ("SAFS_StoreStatus,  Fid    = %u.%u.%u, Host %s:%d, Id %d\n",
3262              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
3263              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3264     FS_LOCK;
3265     AFSCallStats.StoreStatus++, AFSCallStats.TotalCalls++;
3266     FS_UNLOCK;
3267     /*
3268      * Get volume/vnode for the target file; caller's rights to it are
3269      * also returned
3270      */
3271     if ((errorCode =
3272          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
3273                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3274                           &rights, &anyrights))) {
3275         goto Bad_StoreStatus;
3276     }
3277
3278     /* set volume synchronization information */
3279     SetVolumeSync(Sync, volptr);
3280
3281     /* Check if the caller has proper permissions to store status to Fid */
3282     if ((errorCode =
3283          Check_PermissionRights(targetptr, client, rights, CHK_STORESTATUS,
3284                                 InStatus))) {
3285         goto Bad_StoreStatus;
3286     }
3287     /*
3288      * Check for a symbolic link; we can't chmod these (otherwise could
3289      * change a symlink to a mt pt or vice versa)
3290      */
3291     if (targetptr->disk.type == vSymlink && (InStatus->Mask & AFS_SETMODE)) {
3292         errorCode = EINVAL;
3293         goto Bad_StoreStatus;
3294     }
3295
3296     /* Update the status of the target's vnode */
3297     Update_TargetVnodeStatus(targetptr, TVS_SSTATUS, client, InStatus,
3298                              (parentwhentargetnotdir ? parentwhentargetnotdir
3299                               : targetptr), volptr, 0);
3300
3301     /* convert the write lock to a read lock before breaking callbacks */
3302     VVnodeWriteToRead(&errorCode, targetptr);
3303     assert(!errorCode || errorCode == VSALVAGE);
3304
3305     /* Break call backs on Fid */
3306     BreakCallBack(client->host, Fid, 0);
3307
3308     /* Return the updated status back to caller */
3309     GetStatus(targetptr, OutStatus, rights, anyrights,
3310               parentwhentargetnotdir);
3311
3312   Bad_StoreStatus:
3313     /* Update and store volume/vnode and parent vnodes back */
3314     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
3315                      volptr, &client);
3316     ViceLog(2, ("SAFS_StoreStatus returns %d\n", errorCode));
3317     return errorCode;
3318
3319 }                               /*SAFSS_StoreStatus */
3320
3321
3322 afs_int32
3323 SRXAFS_StoreStatus(struct rx_call * acall, struct AFSFid * Fid,
3324                    struct AFSStoreStatus * InStatus,
3325                    struct AFSFetchStatus * OutStatus,
3326                    struct AFSVolSync * Sync)
3327 {
3328     afs_int32 code;
3329     struct rx_connection *tcon;
3330     struct host *thost;
3331     struct client *t_client = NULL;     /* tmp ptr to client data */
3332 #if FS_STATS_DETAILED
3333     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3334     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3335     struct timeval elapsedTime; /* Transfer time */
3336
3337     /*
3338      * Set our stats pointer, remember when the RPC operation started, and
3339      * tally the operation.
3340      */
3341     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STORESTATUS]);
3342     FS_LOCK;
3343     (opP->numOps)++;
3344     FS_UNLOCK;
3345     TM_GetTimeOfDay(&opStartTime, 0);
3346 #endif /* FS_STATS_DETAILED */
3347
3348     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3349         goto Bad_StoreStatus;
3350
3351     code = SAFSS_StoreStatus(acall, Fid, InStatus, OutStatus, Sync);
3352
3353   Bad_StoreStatus:
3354     code = CallPostamble(tcon, code, thost);
3355
3356     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3357
3358 #if FS_STATS_DETAILED
3359     TM_GetTimeOfDay(&opStopTime, 0);
3360     if (code == 0) {
3361         FS_LOCK;
3362         (opP->numSuccesses)++;
3363         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3364         fs_stats_AddTo((opP->sumTime), elapsedTime);
3365         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3366         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3367             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3368         }
3369         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3370             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3371         }
3372         FS_UNLOCK;
3373     }
3374 #endif /* FS_STATS_DETAILED */
3375
3376     osi_auditU(acall, StoreStatusEvent, code, 
3377                AUD_ID, t_client ? t_client->ViceId : 0,
3378                AUD_FID, Fid, AUD_END);
3379     return code;
3380
3381 }                               /*SRXAFS_StoreStatus */
3382
3383
3384 /*
3385  * This routine is called exclusively by SRXAFS_RemoveFile(), and should be
3386  * merged in when possible.
3387  */
3388 static afs_int32
3389 SAFSS_RemoveFile(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
3390                  struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
3391 {
3392     Vnode *parentptr = 0;       /* vnode of input Directory */
3393     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
3394     Vnode *targetptr = 0;       /* file to be deleted */
3395     Volume *volptr = 0;         /* pointer to the volume header */
3396     AFSFid fileFid;             /* area for Fid from the directory */
3397     int errorCode = 0;          /* error code */
3398     DirHandle dir;              /* Handle for dir package I/O */
3399     struct client *client = 0;  /* pointer to client structure */
3400     afs_int32 rights, anyrights;        /* rights for this and any user */
3401     struct client *t_client;    /* tmp ptr to client data */
3402     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3403     struct rx_connection *tcon = rx_ConnectionOf(acall);
3404
3405     FidZero(&dir);
3406     /* Get ptr to client data for user Id for logging */
3407     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3408     logHostAddr.s_addr = rxr_HostOf(tcon);
3409     ViceLog(1,
3410             ("SAFS_RemoveFile %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
3411              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3412              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3413     FS_LOCK;
3414     AFSCallStats.RemoveFile++, AFSCallStats.TotalCalls++;
3415     FS_UNLOCK;
3416     /*
3417      * Get volume/vnode for the parent dir; caller's access rights are
3418      * also returned
3419      */
3420     if ((errorCode =
3421          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
3422                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3423                           &rights, &anyrights))) {
3424         goto Bad_RemoveFile;
3425     }
3426     /* set volume synchronization information */
3427     SetVolumeSync(Sync, volptr);
3428
3429     /* Does the caller has delete (& write) access to the parent directory? */
3430     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
3431         goto Bad_RemoveFile;
3432     }
3433
3434     /* Actually delete the desired file */
3435     if ((errorCode =
3436          DeleteTarget(parentptr, volptr, &targetptr, &dir, &fileFid, Name,
3437                       MustNOTBeDIR))) {
3438         goto Bad_RemoveFile;
3439     }
3440
3441     /* Update the vnode status of the parent dir */
3442 #if FS_STATS_DETAILED
3443     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3444                              parentptr->disk.linkCount,
3445                              client->InSameNetwork);
3446 #else
3447     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3448                              parentptr->disk.linkCount);
3449 #endif /* FS_STATS_DETAILED */
3450
3451     /* Return the updated parent dir's status back to caller */
3452     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
3453
3454     /* Handle internal callback state for the parent and the deleted file */
3455     if (targetptr->disk.linkCount == 0) {
3456         /* no references left, discard entry */
3457         DeleteFileCallBacks(&fileFid);
3458         /* convert the parent lock to a read lock before breaking callbacks */
3459         VVnodeWriteToRead(&errorCode, parentptr);
3460         assert(!errorCode || errorCode == VSALVAGE);
3461     } else {
3462         /* convert the parent lock to a read lock before breaking callbacks */
3463         VVnodeWriteToRead(&errorCode, parentptr);
3464         assert(!errorCode || errorCode == VSALVAGE);
3465         /* convert the target lock to a read lock before breaking callbacks */
3466         VVnodeWriteToRead(&errorCode, targetptr);
3467         assert(!errorCode || errorCode == VSALVAGE);
3468         /* tell all the file has changed */
3469         BreakCallBack(client->host, &fileFid, 1);
3470     }
3471
3472     /* break call back on the directory */
3473     BreakCallBack(client->host, DirFid, 0);
3474
3475   Bad_RemoveFile:
3476     /* Update and store volume/vnode and parent vnodes back */
3477     PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr, 
3478                      volptr, &client);
3479     FidZap(&dir);
3480     ViceLog(2, ("SAFS_RemoveFile returns %d\n", errorCode));
3481     return errorCode;
3482
3483 }                               /*SAFSS_RemoveFile */
3484
3485
3486 afs_int32
3487 SRXAFS_RemoveFile(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
3488                   struct AFSFetchStatus * OutDirStatus,
3489                   struct AFSVolSync * Sync)
3490 {
3491     afs_int32 code;
3492     struct rx_connection *tcon;
3493     struct host *thost;
3494     struct client *t_client = NULL;     /* tmp ptr to client data */
3495 #if FS_STATS_DETAILED
3496     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3497     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3498     struct timeval elapsedTime; /* Transfer time */
3499
3500     /*
3501      * Set our stats pointer, remember when the RPC operation started, and
3502      * tally the operation.
3503      */
3504     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_REMOVEFILE]);
3505     FS_LOCK;
3506     (opP->numOps)++;
3507     FS_UNLOCK;
3508     TM_GetTimeOfDay(&opStartTime, 0);
3509 #endif /* FS_STATS_DETAILED */
3510
3511     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3512         goto Bad_RemoveFile;
3513
3514     code = SAFSS_RemoveFile(acall, DirFid, Name, OutDirStatus, Sync);
3515
3516   Bad_RemoveFile:
3517     code = CallPostamble(tcon, code, thost);
3518
3519     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3520
3521 #if FS_STATS_DETAILED
3522     TM_GetTimeOfDay(&opStopTime, 0);
3523     if (code == 0) {
3524         FS_LOCK;
3525         (opP->numSuccesses)++;
3526         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3527         fs_stats_AddTo((opP->sumTime), elapsedTime);
3528         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3529         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3530             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3531         }
3532         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3533             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3534         }
3535         FS_UNLOCK;
3536     }
3537 #endif /* FS_STATS_DETAILED */
3538
3539     osi_auditU(acall, RemoveFileEvent, code, 
3540                AUD_ID, t_client ? t_client->ViceId : 0,
3541                AUD_FID, DirFid, AUD_STR, Name, AUD_END);
3542     return code;
3543
3544 }                               /*SRXAFS_RemoveFile */
3545
3546
3547 /*
3548  * This routine is called exclusively from SRXAFS_CreateFile(), and should
3549  * be merged in when possible.
3550  */
3551 static afs_int32
3552 SAFSS_CreateFile(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
3553                  struct AFSStoreStatus *InStatus, struct AFSFid *OutFid,
3554                  struct AFSFetchStatus *OutFidStatus,
3555                  struct AFSFetchStatus *OutDirStatus,
3556                  struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
3557 {
3558     Vnode *parentptr = 0;       /* vnode of input Directory */
3559     Vnode *targetptr = 0;       /* vnode of the new file */
3560     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
3561     Volume *volptr = 0;         /* pointer to the volume header */
3562     int errorCode = 0;          /* error code */
3563     DirHandle dir;              /* Handle for dir package I/O */
3564     struct client *client = 0;  /* pointer to client structure */
3565     afs_int32 rights, anyrights;        /* rights for this and any user */
3566     struct client *t_client;    /* tmp ptr to client data */
3567     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3568     struct rx_connection *tcon = rx_ConnectionOf(acall);
3569
3570     FidZero(&dir);
3571
3572     /* Get ptr to client data for user Id for logging */
3573     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3574     logHostAddr.s_addr = rxr_HostOf(tcon);
3575     ViceLog(1,
3576             ("SAFS_CreateFile %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
3577              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3578              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3579     FS_LOCK;
3580     AFSCallStats.CreateFile++, AFSCallStats.TotalCalls++;
3581     FS_UNLOCK;
3582     if (!FileNameOK(Name)) {
3583         errorCode = EINVAL;
3584         goto Bad_CreateFile;
3585     }
3586
3587     /*
3588      * Get associated volume/vnode for the parent dir; caller long are
3589      * also returned
3590      */
3591     if ((errorCode =
3592          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
3593                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3594                           &rights, &anyrights))) {
3595         goto Bad_CreateFile;
3596     }
3597
3598     /* set volume synchronization information */
3599     SetVolumeSync(Sync, volptr);
3600
3601     /* Can we write (and insert) onto the parent directory? */
3602     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
3603         goto Bad_CreateFile;
3604     }
3605     /* get a new vnode for the file to be created and set it up */
3606     if ((errorCode =
3607          Alloc_NewVnode(parentptr, &dir, volptr, &targetptr, Name, OutFid,
3608                         vFile, nBlocks(0)))) {
3609         goto Bad_CreateFile;
3610     }
3611
3612     /* update the status of the parent vnode */
3613 #if FS_STATS_DETAILED
3614     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3615                              parentptr->disk.linkCount,
3616                              client->InSameNetwork);
3617 #else
3618     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3619                              parentptr->disk.linkCount);
3620 #endif /* FS_STATS_DETAILED */
3621
3622     /* update the status of the new file's vnode */
3623     Update_TargetVnodeStatus(targetptr, TVS_CFILE, client, InStatus,
3624                              parentptr, volptr, 0);
3625
3626     /* 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 */
3627     GetStatus(targetptr, OutFidStatus, rights | PRSFS_ADMINISTER, anyrights, parentptr);
3628     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
3629
3630     /* convert the write lock to a read lock before breaking callbacks */
3631     VVnodeWriteToRead(&errorCode, parentptr);
3632     assert(!errorCode || errorCode == VSALVAGE);
3633
3634     /* break call back on parent dir */
3635     BreakCallBack(client->host, DirFid, 0);
3636
3637     /* Return a callback promise for the newly created file to the caller */
3638     SetCallBackStruct(AddCallBack(client->host, OutFid), CallBack);
3639
3640   Bad_CreateFile:
3641     /* Update and store volume/vnode and parent vnodes back */
3642     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
3643                            volptr, &client);
3644     FidZap(&dir);
3645     ViceLog(2, ("SAFS_CreateFile returns %d\n", errorCode));
3646     return errorCode;
3647
3648 }                               /*SAFSS_CreateFile */
3649
3650
3651 afs_int32
3652 SRXAFS_CreateFile(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
3653                   struct AFSStoreStatus * InStatus, struct AFSFid * OutFid,
3654                   struct AFSFetchStatus * OutFidStatus,
3655                   struct AFSFetchStatus * OutDirStatus,
3656                   struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
3657 {
3658     afs_int32 code;
3659     struct rx_connection *tcon;
3660     struct host *thost;
3661     struct client *t_client = NULL;     /* tmp ptr to client data */
3662 #if FS_STATS_DETAILED
3663     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3664     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3665     struct timeval elapsedTime; /* Transfer time */
3666
3667     /*
3668      * Set our stats pointer, remember when the RPC operation started, and
3669      * tally the operation.
3670      */
3671     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_CREATEFILE]);
3672     FS_LOCK;
3673     (opP->numOps)++;
3674     FS_UNLOCK;
3675     TM_GetTimeOfDay(&opStartTime, 0);
3676 #endif /* FS_STATS_DETAILED */
3677
3678     memset(OutFid, 0, sizeof(struct AFSFid));
3679
3680     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3681         goto Bad_CreateFile;
3682
3683     code =
3684         SAFSS_CreateFile(acall, DirFid, Name, InStatus, OutFid, OutFidStatus,
3685                          OutDirStatus, CallBack, Sync);
3686
3687   Bad_CreateFile:
3688     code = CallPostamble(tcon, code, thost);
3689
3690     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3691
3692 #if FS_STATS_DETAILED
3693     TM_GetTimeOfDay(&opStopTime, 0);
3694     if (code == 0) {
3695         FS_LOCK;
3696         (opP->numSuccesses)++;
3697         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3698         fs_stats_AddTo((opP->sumTime), elapsedTime);
3699         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3700         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3701             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3702         }
3703         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3704             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3705         }
3706         FS_UNLOCK;
3707     }
3708 #endif /* FS_STATS_DETAILED */
3709
3710     osi_auditU(acall, CreateFileEvent, code, 
3711                AUD_ID, t_client ? t_client->ViceId : 0,
3712                AUD_FID, DirFid, AUD_STR, Name, AUD_FID, OutFid, AUD_END);
3713     return code;
3714
3715 }                               /*SRXAFS_CreateFile */
3716
3717
3718 /*
3719  * This routine is called exclusively from SRXAFS_Rename(), and should be
3720  * merged in when possible.
3721  */
3722 static afs_int32
3723 SAFSS_Rename(struct rx_call *acall, struct AFSFid *OldDirFid, char *OldName,
3724              struct AFSFid *NewDirFid, char *NewName,
3725              struct AFSFetchStatus *OutOldDirStatus,
3726              struct AFSFetchStatus *OutNewDirStatus, struct AFSVolSync *Sync)
3727 {
3728     Vnode *oldvptr = 0;         /* vnode of the old Directory */
3729     Vnode *newvptr = 0;         /* vnode of the new Directory */
3730     Vnode *fileptr = 0;         /* vnode of the file to move */
3731     Vnode *newfileptr = 0;      /* vnode of the file to delete */
3732     Vnode *testvptr = 0;        /* used in directory tree walk */
3733     Vnode *parent = 0;          /* parent for use in SetAccessList */
3734     int errorCode = 0;          /* error code */
3735     int fileCode = 0;           /* used when writing Vnodes */
3736     VnodeId testnode;           /* used in directory tree walk */
3737     AFSFid fileFid;             /* Fid of file to move */
3738     AFSFid newFileFid;          /* Fid of new file */
3739     DirHandle olddir;           /* Handle for dir package I/O */
3740     DirHandle newdir;           /* Handle for dir package I/O */
3741     DirHandle filedir;          /* Handle for dir package I/O */
3742     DirHandle newfiledir;       /* Handle for dir package I/O */
3743     Volume *volptr = 0;         /* pointer to the volume header */
3744     struct client *client = 0;  /* pointer to client structure */
3745     afs_int32 rights, anyrights;        /* rights for this and any user */
3746     afs_int32 newrights;        /* rights for this user */
3747     afs_int32 newanyrights;     /* rights for any user */
3748     int doDelete;               /* deleted the rename target (ref count now 0) */
3749     int code;
3750     struct client *t_client;    /* tmp ptr to client data */
3751     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3752     struct rx_connection *tcon = rx_ConnectionOf(acall);
3753
3754     FidZero(&olddir);
3755     FidZero(&newdir);
3756     FidZero(&filedir);
3757     FidZero(&newfiledir);
3758
3759     /* Get ptr to client data for user Id for logging */
3760     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3761     logHostAddr.s_addr = rxr_HostOf(tcon);
3762     ViceLog(1,
3763             ("SAFS_Rename %s    to %s,  Fid = %u.%u.%u to %u.%u.%u, Host %s:%d, Id %d\n",
3764              OldName, NewName, OldDirFid->Volume, OldDirFid->Vnode,
3765              OldDirFid->Unique, NewDirFid->Volume, NewDirFid->Vnode,
3766              NewDirFid->Unique, inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3767     FS_LOCK;
3768     AFSCallStats.Rename++, AFSCallStats.TotalCalls++;
3769     FS_UNLOCK;
3770     if (!FileNameOK(NewName)) {
3771         errorCode = EINVAL;
3772         goto Bad_Rename;
3773     }
3774     if (OldDirFid->Volume != NewDirFid->Volume) {
3775         DFlush();
3776         errorCode = EXDEV;
3777         goto Bad_Rename;
3778     }
3779     if ((strcmp(OldName, ".") == 0) || (strcmp(OldName, "..") == 0)
3780         || (strcmp(NewName, ".") == 0) || (strcmp(NewName, "..") == 0)
3781         || (strlen(NewName) == 0) || (strlen(OldName) == 0)) {
3782         DFlush();
3783         errorCode = EINVAL;
3784         goto Bad_Rename;
3785     }
3786
3787     if (OldDirFid->Vnode <= NewDirFid->Vnode) {
3788         if ((errorCode =
3789              GetVolumePackage(tcon, OldDirFid, &volptr, &oldvptr, MustBeDIR,
3790                               &parent, &client, WRITE_LOCK, &rights,
3791                               &anyrights))) {
3792             DFlush();
3793             goto Bad_Rename;
3794         }
3795         if (OldDirFid->Vnode == NewDirFid->Vnode) {
3796             newvptr = oldvptr;
3797             newrights = rights, newanyrights = anyrights;
3798         } else
3799             if ((errorCode =
3800                  GetVolumePackage(tcon, NewDirFid, &volptr, &newvptr,
3801                                   MustBeDIR, &parent, &client, WRITE_LOCK,
3802                                   &newrights, &newanyrights))) {
3803             DFlush();
3804             goto Bad_Rename;
3805         }
3806     } else {
3807         if ((errorCode =
3808              GetVolumePackage(tcon, NewDirFid, &volptr, &newvptr, MustBeDIR,
3809                               &parent, &client, WRITE_LOCK, &newrights,
3810                               &newanyrights))) {
3811             DFlush();
3812             goto Bad_Rename;
3813         }
3814         if ((errorCode =
3815              GetVolumePackage(tcon, OldDirFid, &volptr, &oldvptr, MustBeDIR,
3816                               &parent, &client, WRITE_LOCK, &rights,
3817                               &anyrights))) {
3818             DFlush();
3819             goto Bad_Rename;
3820         }
3821     }
3822
3823     /* set volume synchronization information */
3824     SetVolumeSync(Sync, volptr);
3825
3826     if ((errorCode = CheckWriteMode(oldvptr, rights, PRSFS_DELETE))) {
3827         goto Bad_Rename;
3828     }
3829     if ((errorCode = CheckWriteMode(newvptr, newrights, PRSFS_INSERT))) {
3830         goto Bad_Rename;
3831     }
3832
3833     /* The CopyOnWrite might return ENOSPC ( disk full). Even if the second
3834      *  call to CopyOnWrite returns error, it is not necessary to revert back
3835      *  the effects of the first call because the contents of the volume is 
3836      *  not modified, it is only replicated.
3837      */
3838     if (oldvptr->disk.cloned) {
3839         ViceLog(25, ("Rename : calling CopyOnWrite on  old dir\n"));
3840         if ((errorCode = CopyOnWrite(oldvptr, volptr)))
3841             goto Bad_Rename;
3842     }
3843     SetDirHandle(&olddir, oldvptr);
3844     if (newvptr->disk.cloned) {
3845         ViceLog(25, ("Rename : calling CopyOnWrite on  new dir\n"));
3846         if ((errorCode = CopyOnWrite(newvptr, volptr)))
3847             goto Bad_Rename;
3848     }
3849
3850     SetDirHandle(&newdir, newvptr);
3851
3852     /* Lookup the file to delete its vnode */
3853     if (Lookup(&olddir, OldName, &fileFid)) {
3854         errorCode = ENOENT;
3855         goto Bad_Rename;
3856     }
3857     if (fileFid.Vnode == oldvptr->vnodeNumber
3858         || fileFid.Vnode == newvptr->vnodeNumber) {
3859         errorCode = FSERR_ELOOP;
3860         goto Bad_Rename;
3861     }
3862     fileFid.Volume = V_id(volptr);
3863     fileptr = VGetVnode(&errorCode, volptr, fileFid.Vnode, WRITE_LOCK);
3864     if (errorCode != 0) {
3865         ViceLog(0,
3866                 ("SAFSS_Rename(): Error in VGetVnode() for old file %s, code %d\n",
3867                  OldName, errorCode));
3868         VTakeOffline(volptr);
3869         goto Bad_Rename;
3870     }
3871     if (fileptr->disk.uniquifier != fileFid.Unique) {
3872         ViceLog(0,
3873                 ("SAFSS_Rename(): Old file %s uniquifier mismatch\n",
3874                  OldName));
3875         VTakeOffline(volptr);
3876         errorCode = EIO;
3877         goto Bad_Rename;
3878     }
3879
3880     if (fileptr->disk.type != vDirectory && oldvptr != newvptr
3881         && fileptr->disk.linkCount != 1) {
3882         /*
3883          * Hard links exist to this file - cannot move one of the links to
3884          * a new directory because of AFS restrictions (this is the same
3885          * reason that links cannot be made across directories, i.e.
3886          * access lists)
3887          */
3888         errorCode = EXDEV;
3889         goto Bad_Rename;
3890     }
3891
3892     /* Lookup the new file  */
3893     if (!(Lookup(&newdir, NewName, &newFileFid))) {
3894         if (readonlyServer) {
3895             errorCode = VREADONLY;
3896             goto Bad_Rename;
3897         }
3898         if (!(newrights & PRSFS_DELETE)) {
3899             errorCode = EACCES;
3900             goto Bad_Rename;
3901         }
3902         if (newFileFid.Vnode == oldvptr->vnodeNumber
3903             || newFileFid.Vnode == newvptr->vnodeNumber
3904             || newFileFid.Vnode == fileFid.Vnode) {
3905             errorCode = EINVAL;
3906             goto Bad_Rename;
3907         }
3908         newFileFid.Volume = V_id(volptr);
3909         newfileptr =
3910             VGetVnode(&errorCode, volptr, newFileFid.Vnode, WRITE_LOCK);
3911         if (errorCode != 0) {
3912             ViceLog(0,
3913                     ("SAFSS_Rename(): Error in VGetVnode() for new file %s, code %d\n",
3914                      NewName, errorCode));
3915             VTakeOffline(volptr);
3916             goto Bad_Rename;
3917         }
3918         if (fileptr->disk.uniquifier != fileFid.Unique) {
3919             ViceLog(0,
3920                     ("SAFSS_Rename(): New file %s uniquifier mismatch\n",
3921                      NewName));
3922             VTakeOffline(volptr);
3923             errorCode = EIO;
3924             goto Bad_Rename;
3925         }
3926         SetDirHandle(&newfiledir, newfileptr);
3927         /* Now check that we're moving directories over directories properly, etc.
3928          * return proper POSIX error codes:
3929          * if fileptr is a file and new is a dir: EISDIR.
3930          * if fileptr is a dir and new is a file: ENOTDIR.
3931          * Also, dir to be removed must be empty, of course.
3932          */
3933         if (newfileptr->disk.type == vDirectory) {
3934             if (fileptr->disk.type != vDirectory) {
3935                 errorCode = EISDIR;
3936                 goto Bad_Rename;
3937             }
3938             if ((IsEmpty(&newfiledir))) {
3939                 errorCode = EEXIST;
3940                 goto Bad_Rename;
3941             }
3942         } else {
3943             if (fileptr->disk.type == vDirectory) {
3944                 errorCode = ENOTDIR;
3945                 goto Bad_Rename;
3946             }
3947         }
3948     }
3949
3950     /*
3951      * ok - now we check that the old name is not above new name in the
3952      * directory structure.  This is to prevent removing a subtree alltogether
3953      */
3954     if ((oldvptr != newvptr) && (fileptr->disk.type == vDirectory)) {
3955         afs_int32 forpass = 0, vnum = 0, top = 0;
3956         for (testnode = newvptr->disk.parent; testnode != 0; forpass++) {
3957             if (testnode > vnum) vnum = testnode;
3958             if (forpass > vnum) {
3959                 errorCode = FSERR_ELOOP;
3960                 goto Bad_Rename;
3961             }
3962             if (testnode == oldvptr->vnodeNumber) {
3963                 testnode = oldvptr->disk.parent;
3964                 continue;
3965             }
3966             if ((testnode == fileptr->vnodeNumber)
3967                 || (testnode == newvptr->vnodeNumber)) {
3968                 errorCode = FSERR_ELOOP;
3969                 goto Bad_Rename;
3970             }
3971             if ((newfileptr) && (testnode == newfileptr->vnodeNumber)) {
3972                 errorCode = FSERR_ELOOP;
3973                 goto Bad_Rename;
3974             }
3975             if (testnode == 1) top = 1;
3976             testvptr = VGetVnode(&errorCode, volptr, testnode, READ_LOCK);
3977             assert(errorCode == 0);
3978             testnode = testvptr->disk.parent;
3979             VPutVnode(&errorCode, testvptr);
3980             if ((top == 1) && (testnode != 0)) {
3981                 VTakeOffline(volptr);
3982                 errorCode = EIO;
3983                 goto Bad_Rename;
3984             }
3985             assert(errorCode == 0);
3986         }
3987     }
3988     /* Do the CopyonWrite first before modifying anything else. Copying is
3989      *  required because we may have to change entries for .. 
3990      */
3991     if ((fileptr->disk.type == vDirectory) && (fileptr->disk.cloned)) {
3992         ViceLog(25, ("Rename : calling CopyOnWrite on  target dir\n"));
3993         if ((errorCode = CopyOnWrite(fileptr, volptr)))
3994             goto Bad_Rename;
3995     }
3996
3997     /* If the new name exists already, delete it and the file it points to */
3998     doDelete = 0;
3999     if (newfileptr) {
4000         /* Delete NewName from its directory */
4001         code = Delete(&newdir, NewName);
4002         assert(code == 0);
4003
4004         /* Drop the link count */
4005         newfileptr->disk.linkCount--;
4006         if (newfileptr->disk.linkCount == 0) {  /* Link count 0 - delete */
4007             afs_fsize_t newSize;
4008             VN_GET_LEN(newSize, newfileptr);
4009             VAdjustDiskUsage((Error *) & errorCode, volptr,
4010                              (afs_sfsize_t) - nBlocks(newSize), 0);
4011             if (VN_GET_INO(newfileptr)) {
4012                 IH_REALLYCLOSE(newfileptr->handle);
4013                 errorCode =
4014                     IH_DEC(V_linkHandle(volptr), VN_GET_INO(newfileptr),
4015                            V_parentId(volptr));
4016                 IH_RELEASE(newfileptr->handle);
4017                 if (errorCode == -1) {
4018                     ViceLog(0,
4019                             ("Del: inode=%s, name=%s, errno=%d\n",
4020                              PrintInode(NULL, VN_GET_INO(newfileptr)),
4021                              NewName, errno));
4022                     if ((errno != ENOENT) && (errno != EIO)
4023                         && (errno != ENXIO))
4024                         ViceLog(0, ("Do we need to fsck?"));
4025                 }
4026             }
4027             VN_SET_INO(newfileptr, (Inode) 0);
4028             newfileptr->delete = 1;     /* Mark NewName vnode to delete */
4029             doDelete = 1;
4030         } else {
4031             /* Link count did not drop to zero.
4032              * Mark NewName vnode as changed - updates stime.
4033              */
4034             newfileptr->changed_newTime = 1;
4035         }
4036     }
4037
4038     /*
4039      * If the create below fails, and the delete above worked, we have
4040      * removed the new name and not replaced it.  This is not very likely,
4041      * but possible.  We could try to put the old file back, but it is
4042      * highly unlikely that it would work since it would involve issuing
4043      * another create.
4044      */
4045     if ((errorCode = Create(&newdir, (char *)NewName, &fileFid)))
4046         goto Bad_Rename;
4047
4048     /* Delete the old name */
4049     assert(Delete(&olddir, (char *)OldName) == 0);
4050
4051     /* if the directory length changes, reflect it in the statistics */
4052 #if FS_STATS_DETAILED
4053     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
4054                              oldvptr->disk.linkCount, client->InSameNetwork);
4055     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
4056                              newvptr->disk.linkCount, client->InSameNetwork);
4057 #else
4058     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
4059                              oldvptr->disk.linkCount);
4060     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
4061                              newvptr->disk.linkCount);
4062 #endif /* FS_STATS_DETAILED */
4063
4064     if (oldvptr == newvptr)
4065         oldvptr->disk.dataVersion--;    /* Since it was bumped by 2! */
4066
4067     fileptr->disk.parent = newvptr->vnodeNumber;
4068     fileptr->changed_newTime = 1;       /* status change of moved file */
4069
4070     /* if we are dealing with a rename of a directory */
4071     if (fileptr->disk.type == vDirectory) {
4072         assert(!fileptr->disk.cloned);
4073         SetDirHandle(&filedir, fileptr);
4074         /* fix .. to point to the correct place */
4075         Delete(&filedir, ".."); /* No assert--some directories may be bad */
4076         assert(Create(&filedir, "..", NewDirFid) == 0);
4077         fileptr->disk.dataVersion++;
4078         /* if the parent directories are different the link counts have to be   */
4079         /* changed due to .. in the renamed directory */
4080         if (oldvptr != newvptr) {
4081             oldvptr->disk.linkCount--;
4082             newvptr->disk.linkCount++;
4083         }
4084     }
4085
4086     /* set up return status */
4087     GetStatus(oldvptr, OutOldDirStatus, rights, anyrights, 0);
4088     GetStatus(newvptr, OutNewDirStatus, newrights, newanyrights, 0);
4089     if (newfileptr && doDelete) {
4090         DeleteFileCallBacks(&newFileFid);       /* no other references */
4091     }
4092
4093     DFlush();
4094
4095     /* convert the write locks to a read locks before breaking callbacks */
4096     VVnodeWriteToRead(&errorCode, newvptr);
4097     assert(!errorCode || errorCode == VSALVAGE);
4098     if (oldvptr != newvptr) {
4099         VVnodeWriteToRead(&errorCode, oldvptr);
4100         assert(!errorCode || errorCode == VSALVAGE);
4101     }
4102     if (newfileptr && !doDelete) {
4103         /* convert the write lock to a read lock before breaking callbacks */
4104         VVnodeWriteToRead(&errorCode, newfileptr);
4105         assert(!errorCode || errorCode == VSALVAGE);
4106     }
4107
4108     /* break call back on NewDirFid, OldDirFid, NewDirFid and newFileFid  */
4109     BreakCallBack(client->host, NewDirFid, 0);
4110     if (oldvptr != newvptr) {
4111         BreakCallBack(client->host, OldDirFid, 0);
4112         if (fileptr->disk.type == vDirectory)   /* if a dir moved, .. changed */
4113             BreakCallBack(client->host, &fileFid, 0);
4114     }
4115     if (newfileptr) {
4116         /* Note:  it is not necessary to break the callback */
4117         if (doDelete)
4118             DeleteFileCallBacks(&newFileFid);   /* no other references */
4119         else
4120             /* other's still exist (with wrong link count) */
4121             BreakCallBack(client->host, &newFileFid, 1);
4122     }
4123
4124   Bad_Rename:
4125     if (newfileptr) {
4126         VPutVnode(&fileCode, newfileptr);
4127         assert(fileCode == 0);
4128     }
4129     (void)PutVolumePackage(fileptr, (newvptr && newvptr != oldvptr ? 
4130                                      newvptr : 0), oldvptr, volptr, &client);
4131     FidZap(&olddir);
4132     FidZap(&newdir);
4133     FidZap(&filedir);
4134     FidZap(&newfiledir);
4135     ViceLog(2, ("SAFS_Rename returns %d\n", errorCode));
4136     return errorCode;
4137
4138 }                               /*SAFSS_Rename */
4139
4140
4141 afs_int32
4142 SRXAFS_Rename(struct rx_call * acall, struct AFSFid * OldDirFid,
4143               char *OldName, struct AFSFid * NewDirFid, char *NewName,
4144               struct AFSFetchStatus * OutOldDirStatus,
4145               struct AFSFetchStatus * OutNewDirStatus,
4146               struct AFSVolSync * Sync)
4147 {
4148     afs_int32 code;
4149     struct rx_connection *tcon;
4150     struct host *thost;
4151     struct client *t_client = NULL;     /* tmp ptr to client data */
4152 #if FS_STATS_DETAILED
4153     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4154     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4155     struct timeval elapsedTime; /* Transfer time */
4156
4157     /*
4158      * Set our stats pointer, remember when the RPC operation started, and
4159      * tally the operation.
4160      */
4161     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_RENAME]);
4162     FS_LOCK;
4163     (opP->numOps)++;
4164     FS_UNLOCK;
4165     TM_GetTimeOfDay(&opStartTime, 0);
4166 #endif /* FS_STATS_DETAILED */
4167
4168     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4169         goto Bad_Rename;
4170
4171     code =
4172         SAFSS_Rename(acall, OldDirFid, OldName, NewDirFid, NewName,
4173                      OutOldDirStatus, OutNewDirStatus, Sync);
4174
4175   Bad_Rename:
4176     code = CallPostamble(tcon, code, thost);
4177
4178     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4179
4180 #if FS_STATS_DETAILED
4181     TM_GetTimeOfDay(&opStopTime, 0);
4182     if (code == 0) {
4183         FS_LOCK;
4184         (opP->numSuccesses)++;
4185         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4186         fs_stats_AddTo((opP->sumTime), elapsedTime);
4187         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4188         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4189             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4190         }
4191         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4192             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4193         }
4194         FS_UNLOCK;
4195     }
4196 #endif /* FS_STATS_DETAILED */
4197
4198     osi_auditU(acall, RenameFileEvent, code, 
4199                AUD_ID, t_client ? t_client->ViceId : 0,
4200                AUD_FID, OldDirFid, AUD_STR, OldName, 
4201                AUD_FID, NewDirFid, AUD_STR, NewName, AUD_END);
4202     return code;
4203
4204 }                               /*SRXAFS_Rename */
4205
4206
4207 /*
4208  * This routine is called exclusively by SRXAFS_Symlink(), and should be
4209  * merged into it when possible.
4210  */
4211 static afs_int32
4212 SAFSS_Symlink(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4213               char *LinkContents, struct AFSStoreStatus *InStatus,
4214               struct AFSFid *OutFid, struct AFSFetchStatus *OutFidStatus,
4215               struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4216 {
4217     Vnode *parentptr = 0;       /* vnode of input Directory */
4218     Vnode *targetptr = 0;       /* vnode of the new link */
4219     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4220     int errorCode = 0;          /* error code */
4221     int len, code = 0;
4222     DirHandle dir;              /* Handle for dir package I/O */
4223     Volume *volptr = 0;         /* pointer to the volume header */
4224     struct client *client = 0;  /* pointer to client structure */
4225     afs_int32 rights, anyrights;        /* rights for this and any user */
4226     struct client *t_client;    /* tmp ptr to client data */
4227     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4228     FdHandle_t *fdP;
4229     struct rx_connection *tcon = rx_ConnectionOf(acall);
4230
4231     FidZero(&dir);
4232
4233     /* Get ptr to client data for user Id for logging */
4234     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4235     logHostAddr.s_addr = rxr_HostOf(tcon);
4236     ViceLog(1,
4237             ("SAFS_Symlink %s to %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4238              LinkContents, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4239              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4240     FS_LOCK;
4241     AFSCallStats.Symlink++, AFSCallStats.TotalCalls++;
4242     FS_UNLOCK;
4243     if (!FileNameOK(Name)) {
4244         errorCode = EINVAL;
4245         goto Bad_SymLink;
4246     }
4247
4248     /*
4249      * Get the vnode and volume for the parent dir along with the caller's
4250      * rights to it
4251      */
4252     if ((errorCode =
4253          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4254                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4255                           &rights, &anyrights))) {
4256         goto Bad_SymLink;
4257     }
4258
4259     /* set volume synchronization information */
4260     SetVolumeSync(Sync, volptr);
4261
4262     /* Does the caller has insert (and write) access to the parent directory? */
4263     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4264         goto Bad_SymLink;
4265     }
4266
4267     /*
4268      * If we're creating a mount point (any x bits clear), we must have
4269      * administer access to the directory, too.  Always allow sysadmins
4270      * to do this.
4271      */
4272     if ((InStatus->Mask & AFS_SETMODE) && !(InStatus->UnixModeBits & 0111)) {
4273         if (readonlyServer) {
4274             errorCode = VREADONLY;
4275             goto Bad_SymLink;
4276         }
4277         /*
4278          * We have a mountpoint, 'cause we're trying to set the Unix mode
4279          * bits to something with some x bits missing (default mode bits
4280          * if AFS_SETMODE is false is 0777)
4281          */
4282         if (VanillaUser(client) && !(rights & PRSFS_ADMINISTER)) {
4283             errorCode = EACCES;
4284             goto Bad_SymLink;
4285         }
4286     }
4287
4288     /* get a new vnode for the symlink and set it up */
4289     if ((errorCode =
4290          Alloc_NewVnode(parentptr, &dir, volptr, &targetptr, Name, OutFid,
4291                         vSymlink, nBlocks(strlen((char *)LinkContents))))) {
4292         goto Bad_SymLink;
4293     }
4294
4295     /* update the status of the parent vnode */
4296 #if FS_STATS_DETAILED
4297     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4298                              parentptr->disk.linkCount,
4299                              client->InSameNetwork);
4300 #else
4301     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4302                              parentptr->disk.linkCount);
4303 #endif /* FS_STATS_DETAILED */
4304
4305     /* update the status of the new symbolic link file vnode */
4306     Update_TargetVnodeStatus(targetptr, TVS_SLINK, client, InStatus,
4307                              parentptr, volptr, strlen((char *)LinkContents));
4308
4309     /* Write the contents of the symbolic link name into the target inode */
4310     fdP = IH_OPEN(targetptr->handle);
4311     assert(fdP != NULL);
4312     len = strlen((char *) LinkContents);
4313      code = (len == FDH_WRITE(fdP, (char *) LinkContents, len)) ? 0 : VDISKFULL;
4314      if (code) ViceLog(0, ("SAFSS_Symlink FDH_WRITE failed for len=%d, Fid=%u.%d.%d\n", len, OutFid->Volume, OutFid->Vnode, OutFid->Unique));
4315     FDH_CLOSE(fdP);
4316     /*
4317      * Set up and return modified status for the parent dir and new symlink
4318      * to caller.
4319      */
4320     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4321     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4322
4323     /* convert the write lock to a read lock before breaking callbacks */
4324     VVnodeWriteToRead(&errorCode, parentptr);
4325     assert(!errorCode || errorCode == VSALVAGE);
4326
4327     /* break call back on the parent dir */
4328     BreakCallBack(client->host, DirFid, 0);
4329
4330   Bad_SymLink:
4331     /* Write the all modified vnodes (parent, new files) and volume back */
4332     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4333                            volptr, &client);
4334     FidZap(&dir);
4335     ViceLog(2, ("SAFS_Symlink returns %d\n", errorCode));
4336     return ( errorCode ? errorCode : code );
4337
4338 }                               /*SAFSS_Symlink */
4339
4340
4341 afs_int32
4342 SRXAFS_Symlink(acall, DirFid, Name, LinkContents, InStatus, OutFid,
4343                OutFidStatus, OutDirStatus, Sync)
4344      struct AFSVolSync *Sync;
4345      struct rx_call *acall;     /* Rx call */
4346      struct AFSFid *DirFid;     /* Parent dir's fid */
4347      char *Name;                /* File name to create */
4348      char *LinkContents;        /* Contents of the new created file */
4349      struct AFSStoreStatus *InStatus;   /* Input status for the new symbolic link */
4350      struct AFSFid *OutFid;     /* Fid for newly created symbolic link */
4351      struct AFSFetchStatus *OutFidStatus;       /* Output status for new symbolic link */
4352      struct AFSFetchStatus *OutDirStatus;       /* Output status for parent dir */
4353
4354 {
4355     afs_int32 code;
4356     struct rx_connection *tcon;
4357     struct host *thost;
4358     struct client *t_client = NULL;     /* tmp ptr to client data */
4359 #if FS_STATS_DETAILED
4360     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4361     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4362     struct timeval elapsedTime; /* Transfer time */
4363
4364     /*
4365      * Set our stats pointer, remember when the RPC operation started, and
4366      * tally the operation.
4367      */
4368     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SYMLINK]);
4369     FS_LOCK;
4370     (opP->numOps)++;
4371     FS_UNLOCK;
4372     TM_GetTimeOfDay(&opStartTime, 0);
4373 #endif /* FS_STATS_DETAILED */
4374
4375     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4376         goto Bad_Symlink;
4377
4378     code =
4379         SAFSS_Symlink(acall, DirFid, Name, LinkContents, InStatus, OutFid,
4380                       OutFidStatus, OutDirStatus, Sync);
4381
4382   Bad_Symlink:
4383     code = CallPostamble(tcon, code, thost);
4384
4385     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4386
4387 #if FS_STATS_DETAILED
4388     TM_GetTimeOfDay(&opStopTime, 0);
4389     if (code == 0) {
4390         FS_LOCK;
4391         (opP->numSuccesses)++;
4392         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4393         fs_stats_AddTo((opP->sumTime), elapsedTime);
4394         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4395         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4396             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4397         }
4398         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4399             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4400         }
4401         FS_UNLOCK;
4402     }
4403 #endif /* FS_STATS_DETAILED */
4404
4405     osi_auditU(acall, SymlinkEvent, code, 
4406                AUD_ID, t_client ? t_client->ViceId : 0, 
4407                AUD_FID, DirFid, AUD_STR, Name,
4408                AUD_FID, OutFid, AUD_STR, LinkContents, AUD_END);
4409     return code;
4410
4411 }                               /*SRXAFS_Symlink */
4412
4413
4414 /*
4415  * This routine is called exclusively by SRXAFS_Link(), and should be
4416  * merged into it when possible.
4417  */
4418 static afs_int32
4419 SAFSS_Link(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4420            struct AFSFid *ExistingFid, struct AFSFetchStatus *OutFidStatus,
4421            struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4422 {
4423     Vnode *parentptr = 0;       /* vnode of input Directory */
4424     Vnode *targetptr = 0;       /* vnode of the new file */
4425     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4426     Volume *volptr = 0;         /* pointer to the volume header */
4427     int errorCode = 0;          /* error code */
4428     DirHandle dir;              /* Handle for dir package I/O */
4429     struct client *client = 0;  /* pointer to client structure */
4430     afs_int32 rights, anyrights;        /* rights for this and any user */
4431     struct client *t_client;    /* tmp ptr to client data */
4432     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4433     struct rx_connection *tcon = rx_ConnectionOf(acall);
4434
4435     FidZero(&dir);
4436
4437     /* Get ptr to client data for user Id for logging */
4438     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4439     logHostAddr.s_addr = rxr_HostOf(tcon);
4440     ViceLog(1,
4441             ("SAFS_Link %s,     Did = %u.%u.%u, Fid = %u.%u.%u, Host %s:%d, Id %d\n",
4442              Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4443              ExistingFid->Volume, ExistingFid->Vnode, ExistingFid->Unique,
4444              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4445     FS_LOCK;
4446     AFSCallStats.Link++, AFSCallStats.TotalCalls++;
4447     FS_UNLOCK;
4448     if (DirFid->Volume != ExistingFid->Volume) {
4449         errorCode = EXDEV;
4450         goto Bad_Link;
4451     }
4452     if (!FileNameOK(Name)) {
4453         errorCode = EINVAL;
4454         goto Bad_Link;
4455     }
4456
4457     /*
4458      * Get the vnode and volume for the parent dir along with the caller's
4459      * rights to it
4460      */
4461     if ((errorCode =
4462          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4463                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4464                           &rights, &anyrights))) {
4465         goto Bad_Link;
4466     }
4467
4468     /* set volume synchronization information */
4469     SetVolumeSync(Sync, volptr);
4470
4471     /* Can the caller insert into the parent directory? */
4472     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4473         goto Bad_Link;
4474     }
4475
4476     if (((DirFid->Vnode & 1) && (ExistingFid->Vnode & 1)) || (DirFid->Vnode == ExistingFid->Vnode)) {   /* at present, */
4477         /* AFS fileservers always have directory vnodes that are odd.   */
4478         errorCode = EISDIR;
4479         goto Bad_Link;
4480     }
4481
4482     /* get the file vnode  */
4483     if ((errorCode =
4484          CheckVnode(ExistingFid, &volptr, &targetptr, WRITE_LOCK))) {
4485         goto Bad_Link;
4486     }
4487     if (targetptr->disk.type != vFile) {
4488         errorCode = EISDIR;
4489         goto Bad_Link;
4490     }
4491     if (targetptr->disk.parent != DirFid->Vnode) {
4492         errorCode = EXDEV;
4493         goto Bad_Link;
4494     }
4495     if (parentptr->disk.cloned) {
4496         ViceLog(25, ("Link : calling CopyOnWrite on  target dir\n"));
4497         if ((errorCode = CopyOnWrite(parentptr, volptr)))
4498             goto Bad_Link;      /* disk full error */
4499     }
4500
4501     /* add the name to the directory */
4502     SetDirHandle(&dir, parentptr);
4503     if ((errorCode = Create(&dir, (char *)Name, ExistingFid)))
4504         goto Bad_Link;
4505     DFlush();
4506
4507     /* update the status in the parent vnode */
4508     /**WARNING** --> disk.author SHOULDN'T be modified???? */
4509 #if FS_STATS_DETAILED
4510     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4511                              parentptr->disk.linkCount,
4512                              client->InSameNetwork);
4513 #else
4514     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4515                              parentptr->disk.linkCount);
4516 #endif /* FS_STATS_DETAILED */
4517
4518     targetptr->disk.linkCount++;
4519     targetptr->disk.author = client->ViceId;
4520     targetptr->changed_newTime = 1;     /* Status change of linked-to file */
4521
4522     /* set up return status */
4523     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4524     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4525
4526     /* convert the write locks to read locks before breaking callbacks */
4527     VVnodeWriteToRead(&errorCode, targetptr);
4528     assert(!errorCode || errorCode == VSALVAGE);
4529     VVnodeWriteToRead(&errorCode, parentptr);
4530     assert(!errorCode || errorCode == VSALVAGE);
4531
4532     /* break call back on DirFid */
4533     BreakCallBack(client->host, DirFid, 0);
4534     /*
4535      * We also need to break the callback for the file that is hard-linked since part 
4536      * of its status (like linkcount) is changed
4537      */
4538     BreakCallBack(client->host, ExistingFid, 0);
4539
4540   Bad_Link:
4541     /* Write the all modified vnodes (parent, new files) and volume back */
4542     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4543                            volptr, &client);
4544     FidZap(&dir);
4545     ViceLog(2, ("SAFS_Link returns %d\n", errorCode));
4546     return errorCode;
4547
4548 }                               /*SAFSS_Link */
4549
4550
4551 afs_int32
4552 SRXAFS_Link(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4553             struct AFSFid * ExistingFid, struct AFSFetchStatus * OutFidStatus,
4554             struct AFSFetchStatus * OutDirStatus, struct AFSVolSync * Sync)
4555 {
4556     afs_int32 code;
4557     struct rx_connection *tcon;
4558     struct host *thost;
4559     struct client *t_client = NULL;     /* tmp ptr to client data */
4560 #if FS_STATS_DETAILED
4561     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4562     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4563     struct timeval elapsedTime; /* Transfer time */
4564
4565     /*
4566      * Set our stats pointer, remember when the RPC operation started, and
4567      * tally the operation.
4568      */
4569     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_LINK]);
4570     FS_LOCK;
4571     (opP->numOps)++;
4572     FS_UNLOCK;
4573     TM_GetTimeOfDay(&opStartTime, 0);
4574 #endif /* FS_STATS_DETAILED */
4575
4576     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4577         goto Bad_Link;
4578
4579     code =
4580         SAFSS_Link(acall, DirFid, Name, ExistingFid, OutFidStatus,
4581                    OutDirStatus, Sync);
4582
4583   Bad_Link:
4584     code = CallPostamble(tcon, code, thost);
4585
4586     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4587
4588 #if FS_STATS_DETAILED
4589     TM_GetTimeOfDay(&opStopTime, 0);
4590     if (code == 0) {
4591         FS_LOCK;
4592         (opP->numSuccesses)++;
4593         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4594         fs_stats_AddTo((opP->sumTime), elapsedTime);
4595         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4596         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4597             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4598         }
4599         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4600             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4601         }
4602         FS_UNLOCK;
4603     }
4604 #endif /* FS_STATS_DETAILED */
4605
4606     osi_auditU(acall, LinkEvent, code, 
4607                AUD_ID, t_client ? t_client->ViceId : 0,
4608                AUD_FID, DirFid, AUD_STR, Name,
4609                AUD_FID, ExistingFid, AUD_END);
4610     return code;
4611
4612 }                               /*SRXAFS_Link */
4613
4614
4615 /*
4616  * This routine is called exclusively by SRXAFS_MakeDir(), and should be
4617  * merged into it when possible.
4618  */
4619 static afs_int32
4620 SAFSS_MakeDir(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4621               struct AFSStoreStatus *InStatus, struct AFSFid *OutFid,
4622               struct AFSFetchStatus *OutFidStatus,
4623               struct AFSFetchStatus *OutDirStatus,
4624               struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
4625 {
4626     Vnode *parentptr = 0;       /* vnode of input Directory */
4627     Vnode *targetptr = 0;       /* vnode of the new file */
4628     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4629     Volume *volptr = 0;         /* pointer to the volume header */
4630     int errorCode = 0;          /* error code */
4631     struct acl_accessList *newACL;      /* Access list */
4632     int newACLSize;             /* Size of access list */
4633     DirHandle dir;              /* Handle for dir package I/O */
4634     DirHandle parentdir;        /* Handle for dir package I/O */
4635     struct client *client = 0;  /* pointer to client structure */
4636     afs_int32 rights, anyrights;        /* rights for this and any user */
4637     struct client *t_client;    /* tmp ptr to client data */
4638     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4639     struct rx_connection *tcon = rx_ConnectionOf(acall);
4640
4641     FidZero(&dir);
4642     FidZero(&parentdir);
4643
4644     /* Get ptr to client data for user Id for logging */
4645     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4646     logHostAddr.s_addr = rxr_HostOf(tcon);
4647     ViceLog(1,
4648             ("SAFS_MakeDir %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4649              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4650              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4651     FS_LOCK;
4652     AFSCallStats.MakeDir++, AFSCallStats.TotalCalls++;
4653     FS_UNLOCK;
4654     if (!FileNameOK(Name)) {
4655         errorCode = EINVAL;
4656         goto Bad_MakeDir;
4657     }
4658
4659     /*
4660      * Get the vnode and volume for the parent dir along with the caller's
4661      * rights to it.
4662      */
4663     if ((errorCode =
4664          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4665                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4666                           &rights, &anyrights))) {
4667         goto Bad_MakeDir;
4668     }
4669
4670     /* set volume synchronization information */
4671     SetVolumeSync(Sync, volptr);
4672
4673     /* Write access to the parent directory? */
4674 #ifdef DIRCREATE_NEED_WRITE
4675     /*
4676      * requires w access for the user to create a directory. this
4677      * closes a loophole in the current security arrangement, since a
4678      * user with i access only can create a directory and get the
4679      * implcit a access that goes with dir ownership, and proceed to 
4680      * subvert quota in the volume.
4681      */
4682     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))
4683         || (errorCode = CheckWriteMode(parentptr, rights, PRSFS_WRITE))) {
4684 #else
4685     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4686 #endif /* DIRCREATE_NEED_WRITE */
4687         goto Bad_MakeDir;
4688     }
4689 #define EMPTYDIRBLOCKS 2
4690     /* get a new vnode and set it up */
4691     if ((errorCode =
4692          Alloc_NewVnode(parentptr, &parentdir, volptr, &targetptr, Name,
4693                         OutFid, vDirectory, EMPTYDIRBLOCKS))) {
4694         goto Bad_MakeDir;
4695     }
4696
4697     /* Update the status for the parent dir */
4698 #if FS_STATS_DETAILED
4699     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4700                              parentptr->disk.linkCount + 1,
4701                              client->InSameNetwork);
4702 #else
4703     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4704                              parentptr->disk.linkCount + 1);
4705 #endif /* FS_STATS_DETAILED */
4706
4707     /* Point to target's ACL buffer and copy the parent's ACL contents to it */
4708     assert((SetAccessList
4709             (&targetptr, &volptr, &newACL, &newACLSize,
4710              &parentwhentargetnotdir, (AFSFid *) 0, 0)) == 0);
4711     assert(parentwhentargetnotdir == 0);
4712     memcpy((char *)newACL, (char *)VVnodeACL(parentptr), VAclSize(parentptr));
4713
4714     /* update the status for the target vnode */
4715     Update_TargetVnodeStatus(targetptr, TVS_MKDIR, client, InStatus,
4716                              parentptr, volptr, 0);
4717
4718     /* Actually create the New directory in the directory package */
4719     SetDirHandle(&dir, targetptr);
4720     assert(!(MakeDir(&dir, OutFid, DirFid)));
4721     DFlush();
4722     VN_SET_LEN(targetptr, (afs_fsize_t) Length(&dir));
4723
4724     /* set up return status */
4725     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4726     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4727
4728     /* convert the write lock to a read lock before breaking callbacks */
4729     VVnodeWriteToRead(&errorCode, parentptr);
4730     assert(!errorCode || errorCode == VSALVAGE);
4731
4732     /* break call back on DirFid */
4733     BreakCallBack(client->host, DirFid, 0);
4734
4735     /* Return a callback promise to caller */
4736     SetCallBackStruct(AddCallBack(client->host, OutFid), CallBack);
4737
4738   Bad_MakeDir:
4739     /* Write the all modified vnodes (parent, new files) and volume back */
4740     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4741                            volptr, &client);
4742     FidZap(&dir);
4743     FidZap(&parentdir);
4744     ViceLog(2, ("SAFS_MakeDir returns %d\n", errorCode));
4745     return errorCode;
4746
4747 }                               /*SAFSS_MakeDir */
4748
4749
4750 afs_int32
4751 SRXAFS_MakeDir(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4752                struct AFSStoreStatus * InStatus, struct AFSFid * OutFid,
4753                struct AFSFetchStatus * OutFidStatus,
4754                struct AFSFetchStatus * OutDirStatus,
4755                struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
4756 {
4757     afs_int32 code;
4758     struct rx_connection *tcon;
4759     struct host *thost;
4760     struct client *t_client = NULL;     /* tmp ptr to client data */
4761 #if FS_STATS_DETAILED
4762     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4763     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4764     struct timeval elapsedTime; /* Transfer time */
4765
4766     /*
4767      * Set our stats pointer, remember when the RPC operation started, and
4768      * tally the operation.
4769      */
4770     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_MAKEDIR]);
4771     FS_LOCK;
4772     (opP->numOps)++;
4773     FS_UNLOCK;
4774     TM_GetTimeOfDay(&opStartTime, 0);
4775 #endif /* FS_STATS_DETAILED */
4776     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4777         goto Bad_MakeDir;
4778
4779     code =
4780         SAFSS_MakeDir(acall, DirFid, Name, InStatus, OutFid, OutFidStatus,
4781                       OutDirStatus, CallBack, Sync);
4782
4783   Bad_MakeDir:
4784     code = CallPostamble(tcon, code, thost);
4785
4786     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4787
4788 #if FS_STATS_DETAILED
4789     TM_GetTimeOfDay(&opStopTime, 0);
4790     if (code == 0) {
4791         FS_LOCK;
4792         (opP->numSuccesses)++;
4793         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4794         fs_stats_AddTo((opP->sumTime), elapsedTime);
4795         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4796         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4797             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4798         }
4799         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4800             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4801         }
4802         FS_UNLOCK;
4803     }
4804 #endif /* FS_STATS_DETAILED */
4805
4806     osi_auditU(acall, MakeDirEvent, code, 
4807                AUD_ID, t_client ? t_client->ViceId : 0,
4808                AUD_FID, DirFid, AUD_STR, Name,
4809                AUD_FID, OutFid, AUD_END);
4810     return code;
4811
4812 }                               /*SRXAFS_MakeDir */
4813
4814
4815 /*
4816  * This routine is called exclusively by SRXAFS_RemoveDir(), and should be
4817  * merged into it when possible.
4818  */
4819 static afs_int32
4820 SAFSS_RemoveDir(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4821                 struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4822 {
4823     Vnode *parentptr = 0;       /* vnode of input Directory */
4824     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4825     Vnode *targetptr = 0;       /* file to be deleted */
4826     AFSFid fileFid;             /* area for Fid from the directory */
4827     int errorCode = 0;          /* error code */
4828     DirHandle dir;              /* Handle for dir package I/O */
4829     Volume *volptr = 0;         /* pointer to the volume header */
4830     struct client *client = 0;  /* pointer to client structure */
4831     afs_int32 rights, anyrights;        /* rights for this and any user */
4832     Vnode debugvnode1, debugvnode2;
4833     struct client *t_client;    /* tmp ptr to client data */
4834     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4835     struct rx_connection *tcon = rx_ConnectionOf(acall);
4836
4837     FidZero(&dir);
4838
4839     /* Get ptr to client data for user Id for logging */
4840     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4841     logHostAddr.s_addr = rxr_HostOf(tcon);
4842     ViceLog(1,
4843             ("SAFS_RemoveDir    %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4844              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4845              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4846     FS_LOCK;
4847     AFSCallStats.RemoveDir++, AFSCallStats.TotalCalls++;
4848     FS_UNLOCK;
4849     /*
4850      * Get the vnode and volume for the parent dir along with the caller's
4851      * rights to it
4852      */
4853     if ((errorCode =
4854          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4855                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4856                           &rights, &anyrights))) {
4857         goto Bad_RemoveDir;
4858     }
4859     debugvnode1 = *parentptr;
4860
4861     /* set volume synchronization information */
4862     SetVolumeSync(Sync, volptr);
4863
4864     /* Does the caller has delete (&write) access to the parent dir? */
4865     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
4866         goto Bad_RemoveDir;
4867     }
4868
4869     debugvnode2 = *parentptr;
4870     /* Do the actual delete of the desired (empty) directory, Name */
4871     if ((errorCode =
4872          DeleteTarget(parentptr, volptr, &targetptr, &dir, &fileFid, Name,
4873                       MustBeDIR))) {
4874         goto Bad_RemoveDir;
4875     }
4876
4877     /* Update the status for the parent dir; link count is also adjusted */
4878 #if FS_STATS_DETAILED
4879     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4880                              parentptr->disk.linkCount - 1,
4881                              client->InSameNetwork);
4882 #else
4883     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4884                              parentptr->disk.linkCount - 1);
4885 #endif /* FS_STATS_DETAILED */
4886
4887     /* Return to the caller the updated parent dir status */
4888     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4889
4890     /*
4891      * Note: it is not necessary to break the callback on fileFid, since
4892      * refcount is now 0, so no one should be able to refer to the dir
4893      * any longer
4894      */
4895     DeleteFileCallBacks(&fileFid);
4896
4897     /* convert the write lock to a read lock before breaking callbacks */
4898     VVnodeWriteToRead(&errorCode, parentptr);
4899     assert(!errorCode || errorCode == VSALVAGE);
4900
4901     /* break call back on DirFid and fileFid */
4902     BreakCallBack(client->host, DirFid, 0);
4903
4904   Bad_RemoveDir:
4905     /* Write the all modified vnodes (parent, new files) and volume back */
4906     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4907                            volptr, &client);
4908     FidZap(&dir);
4909     ViceLog(2, ("SAFS_RemoveDir returns %d\n", errorCode));
4910     return errorCode;
4911
4912 }                               /*SAFSS_RemoveDir */
4913
4914
4915 afs_int32
4916 SRXAFS_RemoveDir(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4917                  struct AFSFetchStatus * OutDirStatus,
4918                  struct AFSVolSync * Sync)
4919 {
4920     afs_int32 code;
4921     struct rx_connection *tcon;
4922     struct host *thost;
4923     struct client *t_client = NULL;     /* tmp ptr to client data */
4924 #if FS_STATS_DETAILED
4925     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4926     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4927     struct timeval elapsedTime; /* Transfer time */
4928
4929     /*
4930      * Set our stats pointer, remember when the RPC operation started, and
4931      * tally the operation.
4932      */
4933     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_REMOVEDIR]);
4934     FS_LOCK;
4935     (opP->numOps)++;
4936     FS_UNLOCK;
4937     TM_GetTimeOfDay(&opStartTime, 0);
4938 #endif /* FS_STATS_DETAILED */
4939
4940     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4941         goto Bad_RemoveDir;
4942
4943     code = SAFSS_RemoveDir(acall, DirFid, Name, OutDirStatus, Sync);
4944
4945   Bad_RemoveDir:
4946     code = CallPostamble(tcon, code, thost);
4947
4948     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4949
4950 #if FS_STATS_DETAILED
4951     TM_GetTimeOfDay(&opStopTime, 0);
4952     if (code == 0) {
4953         FS_LOCK;
4954         (opP->numSuccesses)++;
4955         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4956         fs_stats_AddTo((opP->sumTime), elapsedTime);
4957         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4958         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4959             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4960         }
4961         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4962             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4963         }
4964         FS_UNLOCK;
4965     }
4966 #endif /* FS_STATS_DETAILED */
4967
4968     osi_auditU(acall, RemoveDirEvent, code, 
4969                AUD_ID, t_client ? t_client->ViceId : 0,
4970                AUD_FID, DirFid, AUD_STR, Name, AUD_END);
4971     return code;
4972
4973 }                               /*SRXAFS_RemoveDir */
4974
4975
4976 /*
4977  * This routine is called exclusively by SRXAFS_SetLock(), and should be
4978  * merged into it when possible.
4979  */
4980 static afs_int32
4981 SAFSS_SetLock(struct rx_call *acall, struct AFSFid *Fid, ViceLockType type,
4982               struct AFSVolSync *Sync)
4983 {
4984     Vnode *targetptr = 0;       /* vnode of input file */
4985     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4986     int errorCode = 0;          /* error code */
4987     Volume *volptr = 0;         /* pointer to the volume header */
4988     struct client *client = 0;  /* pointer to client structure */
4989     afs_int32 rights, anyrights;        /* rights for this and any user */
4990     struct client *t_client;    /* tmp ptr to client data */
4991     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4992     static char *locktype[4] = { "LockRead", "LockWrite", "LockExtend", "LockRelease" };
4993     struct rx_connection *tcon = rx_ConnectionOf(acall);
4994
4995     if (type != LockRead && type != LockWrite) {
4996         errorCode = EINVAL;
4997         goto Bad_SetLock;
4998     }
4999     /* Get ptr to client data for user Id for logging */
5000     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5001     logHostAddr.s_addr = rxr_HostOf(tcon);
5002     ViceLog(1,
5003             ("SAFS_SetLock type = %s Fid = %u.%u.%u, Host %s:%d, Id %d\n",
5004              locktype[(int)type], Fid->Volume, Fid->Vnode, Fid->Unique,
5005              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5006     FS_LOCK;
5007     AFSCallStats.SetLock++, AFSCallStats.TotalCalls++;
5008     FS_UNLOCK;
5009     /*
5010      * Get the vnode and volume for the desired file along with the caller's
5011      * rights to it
5012      */
5013     if ((errorCode =
5014          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5015                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5016                           &rights, &anyrights))) {
5017         goto Bad_SetLock;
5018     }
5019
5020     /* set volume synchronization information */
5021     SetVolumeSync(Sync, volptr);
5022
5023     /* Handle the particular type of set locking, type */
5024     errorCode = HandleLocking(targetptr, client, rights, type);
5025
5026   Bad_SetLock:
5027     /* Write the all modified vnodes (parent, new files) and volume back */
5028     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5029                            volptr, &client);
5030
5031     if ((errorCode == VREADONLY) && (type == LockRead))
5032         errorCode = 0;          /* allow read locks on RO volumes without saving state */
5033
5034     ViceLog(2, ("SAFS_SetLock returns %d\n", errorCode));
5035     return (errorCode);
5036
5037 }                               /*SAFSS_SetLock */
5038
5039
5040 afs_int32
5041 SRXAFS_OldSetLock(struct rx_call * acall, struct AFSFid * Fid,
5042                   ViceLockType type, struct AFSVolSync * Sync)
5043 {
5044     return SRXAFS_SetLock(acall, Fid, type, Sync);
5045 }                               /*SRXAFS_OldSetLock */
5046
5047
5048 afs_int32
5049 SRXAFS_SetLock(struct rx_call * acall, struct AFSFid * Fid, ViceLockType type,
5050                struct AFSVolSync * Sync)
5051 {
5052     afs_int32 code;
5053     struct rx_connection *tcon;
5054     struct host *thost;
5055     struct client *t_client = NULL;     /* tmp ptr to client data */
5056 #if FS_STATS_DETAILED
5057     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5058     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5059     struct timeval elapsedTime; /* Transfer time */
5060
5061     /*
5062      * Set our stats pointer, remember when the RPC operation started, and
5063      * tally the operation.
5064      */
5065     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SETLOCK]);
5066     FS_LOCK;
5067     (opP->numOps)++;
5068     FS_UNLOCK;
5069     TM_GetTimeOfDay(&opStartTime, 0);
5070 #endif /* FS_STATS_DETAILED */
5071
5072     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5073         goto Bad_SetLock;
5074
5075     code = SAFSS_SetLock(acall, Fid, type, Sync);
5076
5077   Bad_SetLock:
5078     code = CallPostamble(tcon, code, thost);
5079
5080     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5081
5082 #if FS_STATS_DETAILED
5083     TM_GetTimeOfDay(&opStopTime, 0);
5084     if (code == 0) {
5085         FS_LOCK;
5086         (opP->numSuccesses)++;
5087         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5088         fs_stats_AddTo((opP->sumTime), elapsedTime);
5089         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5090         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5091             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5092         }
5093         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5094             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5095         }
5096         FS_UNLOCK;
5097     }
5098 #endif /* FS_STATS_DETAILED */
5099
5100     osi_auditU(acall, SetLockEvent, code, 
5101                AUD_ID, t_client ? t_client->ViceId : 0, 
5102                AUD_FID, Fid, AUD_LONG, type, AUD_END);
5103     return code;
5104 }                               /*SRXAFS_SetLock */
5105
5106
5107 /*
5108  * This routine is called exclusively by SRXAFS_ExtendLock(), and should be
5109  * merged into it when possible.
5110  */
5111 static afs_int32
5112 SAFSS_ExtendLock(struct rx_call *acall, struct AFSFid *Fid,
5113                  struct AFSVolSync *Sync)
5114 {
5115     Vnode *targetptr = 0;       /* vnode of input file */
5116     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5117     int errorCode = 0;          /* error code */
5118     Volume *volptr = 0;         /* pointer to the volume header */
5119     struct client *client = 0;  /* pointer to client structure */
5120     afs_int32 rights, anyrights;        /* rights for this and any user */
5121     struct client *t_client;    /* tmp ptr to client data */
5122     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5123     struct rx_connection *tcon = rx_ConnectionOf(acall);
5124
5125     /* Get ptr to client data for user Id for logging */
5126     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5127     logHostAddr.s_addr = rxr_HostOf(tcon);
5128     ViceLog(1,
5129             ("SAFS_ExtendLock Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
5130              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
5131              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5132     FS_LOCK;
5133     AFSCallStats.ExtendLock++, AFSCallStats.TotalCalls++;
5134     FS_UNLOCK;
5135     /*
5136      * Get the vnode and volume for the desired file along with the caller's
5137      * rights to it
5138      */
5139     if ((errorCode =
5140          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5141                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5142                           &rights, &anyrights))) {
5143         goto Bad_ExtendLock;
5144     }
5145
5146     /* set volume synchronization information */
5147     SetVolumeSync(Sync, volptr);
5148
5149     /* Handle the actual lock extension */
5150     errorCode = HandleLocking(targetptr, client, rights, LockExtend);
5151
5152   Bad_ExtendLock:
5153     /* Put back file's vnode and volume */
5154     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5155                            volptr, &client);
5156
5157     if ((errorCode == VREADONLY))       /* presumably, we already granted this lock */
5158         errorCode = 0;          /* under our generous policy re RO vols */
5159
5160     ViceLog(2, ("SAFS_ExtendLock returns %d\n", errorCode));
5161     return (errorCode);
5162
5163 }                               /*SAFSS_ExtendLock */
5164
5165
5166 afs_int32
5167 SRXAFS_OldExtendLock(struct rx_call * acall, struct AFSFid * Fid,
5168                      struct AFSVolSync * Sync)
5169 {
5170     return SRXAFS_ExtendLock(acall, Fid, Sync);
5171 }                               /*SRXAFS_OldExtendLock */
5172
5173
5174 afs_int32
5175 SRXAFS_ExtendLock(struct rx_call * acall, struct AFSFid * Fid,
5176                   struct AFSVolSync * Sync)
5177 {
5178     afs_int32 code;
5179     struct rx_connection *tcon;
5180     struct host *thost;
5181     struct client *t_client = NULL;     /* tmp ptr to client data */
5182 #if FS_STATS_DETAILED
5183     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5184     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5185     struct timeval elapsedTime; /* Transfer time */
5186
5187     /*
5188      * Set our stats pointer, remember when the RPC operation started, and
5189      * tally the operation.
5190      */
5191     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_EXTENDLOCK]);
5192     FS_LOCK;
5193     (opP->numOps)++;
5194     FS_UNLOCK;
5195     TM_GetTimeOfDay(&opStartTime, 0);
5196 #endif /* FS_STATS_DETAILED */
5197
5198     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5199         goto Bad_ExtendLock;
5200
5201     code = SAFSS_ExtendLock(acall, Fid, Sync);
5202
5203   Bad_ExtendLock:
5204     code = CallPostamble(tcon, code, thost);
5205
5206     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5207
5208 #if FS_STATS_DETAILED
5209     TM_GetTimeOfDay(&opStopTime, 0);
5210     if (code == 0) {
5211         FS_LOCK;
5212         (opP->numSuccesses)++;
5213         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5214         fs_stats_AddTo((opP->sumTime), elapsedTime);
5215         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5216         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5217             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5218         }
5219         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5220             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5221         }
5222         FS_UNLOCK;
5223     }
5224 #endif /* FS_STATS_DETAILED */
5225
5226     osi_auditU(acall, ExtendLockEvent, code, 
5227                AUD_ID, t_client ? t_client->ViceId : 0,
5228                AUD_FID, Fid, AUD_END);
5229     return code;
5230
5231 }                               /*SRXAFS_ExtendLock */
5232
5233
5234 /*
5235  * This routine is called exclusively by SRXAFS_ReleaseLock(), and should be
5236  * merged into it when possible.
5237  */
5238 static afs_int32
5239 SAFSS_ReleaseLock(struct rx_call *acall, struct AFSFid *Fid,
5240                   struct AFSVolSync *Sync)
5241 {
5242     Vnode *targetptr = 0;       /* vnode of input file */
5243     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5244     int errorCode = 0;          /* error code */
5245     Volume *volptr = 0;         /* pointer to the volume header */
5246     struct client *client = 0;  /* pointer to client structure */
5247     afs_int32 rights, anyrights;        /* rights for this and any user */
5248     struct client *t_client;    /* tmp ptr to client data */
5249     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5250     struct rx_connection *tcon = rx_ConnectionOf(acall);
5251
5252     /* Get ptr to client data for user Id for logging */
5253     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5254     logHostAddr.s_addr = rxr_HostOf(tcon);
5255     ViceLog(1,
5256             ("SAFS_ReleaseLock Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
5257              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
5258              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5259     FS_LOCK;
5260     AFSCallStats.ReleaseLock++, AFSCallStats.TotalCalls++;
5261     FS_UNLOCK;
5262     /*
5263      * Get the vnode and volume for the desired file along with the caller's
5264      * rights to it
5265      */
5266     if ((errorCode =
5267          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5268                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5269                           &rights, &anyrights))) {
5270         goto Bad_ReleaseLock;
5271     }
5272
5273     /* set volume synchronization information */
5274     SetVolumeSync(Sync, volptr);
5275
5276     /* Handle the actual lock release */
5277     if ((errorCode = HandleLocking(targetptr, client, rights, LockRelease)))
5278         goto Bad_ReleaseLock;
5279
5280     /* if no more locks left, a callback would be triggered here */
5281     if (targetptr->disk.lock.lockCount <= 0) {
5282         /* convert the write lock to a read lock before breaking callbacks */
5283         VVnodeWriteToRead(&errorCode, targetptr);
5284         assert(!errorCode || errorCode == VSALVAGE);
5285         BreakCallBack(client->host, Fid, 0);
5286     }
5287
5288   Bad_ReleaseLock:
5289     /* Put back file's vnode and volume */
5290     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5291                            volptr, &client);
5292
5293     if ((errorCode == VREADONLY))       /* presumably, we already granted this lock */
5294         errorCode = 0;          /* under our generous policy re RO vols */
5295
5296     ViceLog(2, ("SAFS_ReleaseLock returns %d\n", errorCode));
5297     return (errorCode);
5298
5299 }                               /*SAFSS_ReleaseLock */
5300
5301
5302 afs_int32
5303 SRXAFS_OldReleaseLock(struct rx_call * acall, struct AFSFid * Fid,
5304                       struct AFSVolSync * Sync)
5305 {
5306     return SRXAFS_ReleaseLock(acall, Fid, Sync);
5307 }                               /*SRXAFS_OldReleaseLock */
5308
5309
5310 afs_int32
5311 SRXAFS_ReleaseLock(struct rx_call * acall, struct AFSFid * Fid,
5312                    struct AFSVolSync * Sync)
5313 {
5314     afs_int32 code;
5315     struct rx_connection *tcon;
5316     struct host *thost;
5317     struct client *t_client = NULL;     /* tmp ptr to client data */
5318 #if FS_STATS_DETAILED
5319     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5320     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5321     struct timeval elapsedTime; /* Transfer time */
5322
5323     /*
5324      * Set our stats pointer, remember when the RPC operation started, and
5325      * tally the operation.
5326      */
5327     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_RELEASELOCK]);
5328     FS_LOCK;
5329     (opP->numOps)++;
5330     FS_UNLOCK;
5331     TM_GetTimeOfDay(&opStartTime, 0);
5332 #endif /* FS_STATS_DETAILED */
5333
5334     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5335         goto Bad_ReleaseLock;
5336
5337     code = SAFSS_ReleaseLock(acall, Fid, Sync);
5338
5339   Bad_ReleaseLock:
5340     code = CallPostamble(tcon, code, thost);
5341
5342     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5343
5344 #if FS_STATS_DETAILED
5345     TM_GetTimeOfDay(&opStopTime, 0);
5346     if (code == 0) {
5347         FS_LOCK;
5348         (opP->numSuccesses)++;
5349         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5350         fs_stats_AddTo((opP->sumTime), elapsedTime);
5351         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5352         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5353             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5354         }
5355         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5356             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5357         }
5358         FS_UNLOCK;
5359     }
5360 #endif /* FS_STATS_DETAILED */
5361
5362     osi_auditU(acall, ReleaseLockEvent, code, 
5363                AUD_ID, t_client ? t_client->ViceId : 0, 
5364                AUD_FID, Fid, AUD_END);
5365     return code;
5366
5367 }                               /*SRXAFS_ReleaseLock */
5368
5369
5370 void
5371 SetSystemStats(struct AFSStatistics *stats)
5372 {
5373     /* Fix this sometime soon.. */
5374     /* Because hey, it's not like we have a network monitoring protocol... */
5375     struct timeval time;
5376
5377     /* this works on all system types */
5378     TM_GetTimeOfDay(&time, 0);
5379     stats->CurrentTime = time.tv_sec;
5380 }                               /*SetSystemStats */
5381
5382 void
5383 SetAFSStats(struct AFSStatistics *stats)
5384 {
5385     extern afs_int32 StartTime, CurrentConnections;
5386     int seconds;
5387
5388     FS_LOCK;
5389     stats->CurrentMsgNumber = 0;
5390     stats->OldestMsgNumber = 0;
5391     stats->StartTime = StartTime;
5392     stats->CurrentConnections = CurrentConnections;
5393     stats->TotalAFSCalls = AFSCallStats.TotalCalls;
5394     stats->TotalFetchs =
5395         AFSCallStats.FetchData + AFSCallStats.FetchACL +
5396         AFSCallStats.FetchStatus;
5397     stats->FetchDatas = AFSCallStats.FetchData;
5398     stats->FetchedBytes = AFSCallStats.TotalFetchedBytes;
5399     seconds = AFSCallStats.AccumFetchTime / 1000;
5400     if (seconds <= 0)
5401         seconds = 1;
5402     stats->FetchDataRate = AFSCallStats.TotalFetchedBytes / seconds;
5403     stats->TotalStores =
5404         AFSCallStats.StoreData + AFSCallStats.StoreACL +
5405         AFSCallStats.StoreStatus;
5406     stats->StoreDatas = AFSCallStats.StoreData;
5407     stats->StoredBytes = AFSCallStats.TotalStoredBytes;
5408     seconds = AFSCallStats.AccumStoreTime / 1000;
5409     if (seconds <= 0)
5410         seconds = 1;
5411     stats->StoreDataRate = AFSCallStats.TotalStoredBytes / seconds;
5412 #ifdef AFS_NT40_ENV
5413     stats->ProcessSize = -1;    /* TODO: */
5414 #else
5415     stats->ProcessSize = (afs_int32) ((long)sbrk(0) >> 10);
5416 #endif
5417     FS_UNLOCK;
5418     h_GetWorkStats((int *)&(stats->WorkStations),
5419                    (int *)&(stats->ActiveWorkStations), (int *)0,
5420                    (afs_int32) (FT_ApproxTime()) - (15 * 60));
5421
5422 }                               /*SetAFSStats */
5423
5424 /* Get disk related information from all AFS partitions. */
5425
5426 void
5427 SetVolumeStats(struct AFSStatistics *stats)
5428 {
5429     struct DiskPartition *part;
5430     int i = 0;
5431
5432     for (part = DiskPartitionList; part && i < AFS_MSTATDISKS;
5433          part = part->next) {
5434         stats->Disks[i].TotalBlocks = part->totalUsable;
5435         stats->Disks[i].BlocksAvailable = part->free;
5436         memset(stats->Disks[i].Name, 0, AFS_DISKNAMESIZE);
5437         strncpy(stats->Disks[i].Name, part->name, AFS_DISKNAMESIZE);
5438         i++;
5439     }
5440     while (i < AFS_MSTATDISKS) {
5441         stats->Disks[i].TotalBlocks = -1;
5442         i++;
5443     }
5444 }                               /*SetVolumeStats */
5445
5446 afs_int32
5447 SRXAFS_GetStatistics(struct rx_call *acall, struct ViceStatistics *Statistics)
5448 {
5449     afs_int32 code;
5450     struct rx_connection *tcon = rx_ConnectionOf(acall);
5451     struct host *thost;
5452     struct client *t_client = NULL;     /* tmp ptr to client data */
5453 #if FS_STATS_DETAILED
5454     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5455     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5456     struct timeval elapsedTime; /* Transfer time */
5457
5458     /*
5459      * Set our stats pointer, remember when the RPC operation started, and
5460      * tally the operation.
5461      */
5462     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETSTATISTICS]);
5463     FS_LOCK;
5464     (opP->numOps)++;
5465     FS_UNLOCK;
5466     TM_GetTimeOfDay(&opStartTime, 0);
5467 #endif /* FS_STATS_DETAILED */
5468
5469     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
5470         goto Bad_GetStatistics;
5471
5472     ViceLog(1, ("SAFS_GetStatistics Received\n"));
5473     FS_LOCK;
5474     AFSCallStats.GetStatistics++, AFSCallStats.TotalCalls++;
5475     FS_UNLOCK;
5476     memset(Statistics, 0, sizeof(*Statistics));
5477     SetAFSStats((struct AFSStatistics *)Statistics);
5478     SetVolumeStats((struct AFSStatistics *)Statistics);
5479     SetSystemStats((struct AFSStatistics *)Statistics);
5480
5481   Bad_GetStatistics:
5482     code = CallPostamble(tcon, code, thost);
5483
5484     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5485
5486 #if FS_STATS_DETAILED
5487     TM_GetTimeOfDay(&opStopTime, 0);
5488     if (code == 0) {
5489         FS_LOCK;
5490         (opP->numSuccesses)++;
5491         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5492         fs_stats_AddTo((opP->sumTime), elapsedTime);
5493         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5494         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5495             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5496         }
5497         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5498             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5499         }
5500         FS_UNLOCK;
5501     }
5502 #endif /* FS_STATS_DETAILED */
5503
5504     osi_auditU(acall, GetStatisticsEvent, code, 
5505                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5506     return code;
5507 }                               /*SRXAFS_GetStatistics */
5508
5509
5510 /*------------------------------------------------------------------------
5511  * EXPORTED SRXAFS_XStatsVersion
5512  *
5513  * Description:
5514  *      Routine called by the server-side RPC interface to implement
5515  *      pulling out the xstat version number for the File Server.
5516  *
5517  * Arguments:
5518  *      a_versionP : Ptr to the version number variable to set.
5519  *
5520  * Returns:
5521  *      0 (always)
5522  *
5523  * Environment:
5524  *      Nothing interesting.
5525  *
5526  * Side Effects:
5527  *      As advertised.
5528  *------------------------------------------------------------------------*/
5529
5530 afs_int32
5531 SRXAFS_XStatsVersion(struct rx_call * a_call, afs_int32 * a_versionP)
5532 {                               /*SRXAFS_XStatsVersion */
5533
5534     struct client *t_client = NULL;     /* tmp ptr to client data */
5535     struct rx_connection *tcon = rx_ConnectionOf(a_call);
5536 #if FS_STATS_DETAILED
5537     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5538     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5539     struct timeval elapsedTime; /* Transfer time */
5540
5541     /*
5542      * Set our stats pointer, remember when the RPC operation started, and
5543      * tally the operation.
5544      */
5545     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_XSTATSVERSION]);
5546     FS_LOCK;
5547     (opP->numOps)++;
5548     FS_UNLOCK;
5549     TM_GetTimeOfDay(&opStartTime, 0);
5550 #endif /* FS_STATS_DETAILED */
5551
5552     *a_versionP = AFS_XSTAT_VERSION;
5553
5554     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5555
5556 #if FS_STATS_DETAILED
5557     TM_GetTimeOfDay(&opStopTime, 0);
5558     fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5559     fs_stats_AddTo((opP->sumTime), elapsedTime);
5560     fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5561     if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5562         fs_stats_TimeAssign((opP->minTime), elapsedTime);
5563     }
5564     if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5565         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5566     }
5567     FS_LOCK;
5568     (opP->numSuccesses)++;
5569     FS_UNLOCK;
5570 #endif /* FS_STATS_DETAILED */
5571
5572     osi_auditU(a_call, XStatsVersionEvent, 0, 
5573                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5574     return (0);
5575 }                               /*SRXAFS_XStatsVersion */
5576
5577
5578 /*------------------------------------------------------------------------
5579  * PRIVATE FillPerfValues
5580  *
5581  * Description:
5582  *      Routine called to fill a regular performance data structure.
5583  *
5584  * Arguments:
5585  *      a_perfP : Ptr to perf structure to fill
5586  *
5587  * Returns:
5588  *      Nothing.
5589  *
5590  * Environment:
5591  *      Various collections need this info, so the guts were put in
5592  *      this separate routine.
5593  *
5594  * Side Effects:
5595  *      As advertised.
5596  *------------------------------------------------------------------------*/
5597
5598 static void
5599 FillPerfValues(struct afs_PerfStats *a_perfP)
5600 {                               /*FillPerfValues */
5601     afs_uint32 hi, lo;
5602     int dir_Buffers;            /*# buffers in use by dir package */
5603     int dir_Calls;              /*# read calls in dir package */
5604     int dir_IOs;                /*# I/O ops in dir package */
5605
5606     /*
5607      * Vnode cache section.
5608      */
5609     a_perfP->vcache_L_Entries = VnodeClassInfo[vLarge].cacheSize;
5610     a_perfP->vcache_L_Allocs = VnodeClassInfo[vLarge].allocs;
5611     a_perfP->vcache_L_Gets = VnodeClassInfo[vLarge].gets;
5612     a_perfP->vcache_L_Reads = VnodeClassInfo[vLarge].reads;
5613     a_perfP->vcache_L_Writes = VnodeClassInfo[vLarge].writes;
5614     a_perfP->vcache_S_Entries = VnodeClassInfo[vSmall].cacheSize;
5615     a_perfP->vcache_S_Allocs = VnodeClassInfo[vSmall].allocs;
5616     a_perfP->vcache_S_Gets = VnodeClassInfo[vSmall].gets;
5617     a_perfP->vcache_S_Reads = VnodeClassInfo[vSmall].reads;
5618     a_perfP->vcache_S_Writes = VnodeClassInfo[vSmall].writes;
5619     a_perfP->vcache_H_Entries = VStats.hdr_cache_size;
5620     SplitInt64(VStats.hdr_gets, hi, lo);
5621     a_perfP->vcache_H_Gets = lo;
5622     SplitInt64(VStats.hdr_loads, hi, lo);
5623     a_perfP->vcache_H_Replacements = lo;
5624
5625     /*
5626      * Directory section.
5627      */
5628     DStat(&dir_Buffers, &dir_Calls, &dir_IOs);
5629     a_perfP->dir_Buffers = (afs_int32) dir_Buffers;
5630     a_perfP->dir_Calls = (afs_int32) dir_Calls;
5631     a_perfP->dir_IOs = (afs_int32) dir_IOs;
5632
5633     /*
5634      * Rx section.
5635      */
5636     a_perfP->rx_packetRequests = (afs_int32) rx_stats.packetRequests;
5637     a_perfP->rx_noPackets_RcvClass =
5638         (afs_int32) rx_stats.receivePktAllocFailures;
5639     a_perfP->rx_noPackets_SendClass =
5640         (afs_int32) rx_stats.sendPktAllocFailures;
5641     a_perfP->rx_noPackets_SpecialClass =
5642         (afs_int32) rx_stats.specialPktAllocFailures;
5643     a_perfP->rx_socketGreedy = (afs_int32) rx_stats.socketGreedy;
5644     a_perfP->rx_bogusPacketOnRead = (afs_int32) rx_stats.bogusPacketOnRead;
5645     a_perfP->rx_bogusHost = (afs_int32) rx_stats.bogusHost;
5646     a_perfP->rx_noPacketOnRead = (afs_int32) rx_stats.noPacketOnRead;
5647     a_perfP->rx_noPacketBuffersOnRead =
5648         (afs_int32) rx_stats.noPacketBuffersOnRead;
5649     a_perfP->rx_selects = (afs_int32) rx_stats.selects;
5650     a_perfP->rx_sendSelects = (afs_int32) rx_stats.sendSelects;
5651     a_perfP->rx_packetsRead_RcvClass =
5652         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_RECEIVE];
5653     a_perfP->rx_packetsRead_SendClass =
5654         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_SEND];
5655     a_perfP->rx_packetsRead_SpecialClass =
5656         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_SPECIAL];
5657     a_perfP->rx_dataPacketsRead = (afs_int32) rx_stats.dataPacketsRead;
5658     a_perfP->rx_ackPacketsRead = (afs_int32) rx_stats.ackPacketsRead;
5659     a_perfP->rx_dupPacketsRead = (afs_int32) rx_stats.dupPacketsRead;
5660     a_perfP->rx_spuriousPacketsRead =
5661         (afs_int32) rx_stats.spuriousPacketsRead;
5662     a_perfP->rx_packetsSent_RcvClass =
5663         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_RECEIVE];
5664     a_perfP->rx_packetsSent_SendClass =
5665         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_SEND];
5666     a_perfP->rx_packetsSent_SpecialClass =
5667         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_SPECIAL];
5668     a_perfP->rx_ackPacketsSent = (afs_int32) rx_stats.ackPacketsSent;
5669     a_perfP->rx_pingPacketsSent = (afs_int32) rx_stats.pingPacketsSent;
5670     a_perfP->rx_abortPacketsSent = (afs_int32) rx_stats.abortPacketsSent;
5671     a_perfP->rx_busyPacketsSent = (afs_int32) rx_stats.busyPacketsSent;
5672     a_perfP->rx_dataPacketsSent = (afs_int32) rx_stats.dataPacketsSent;
5673     a_perfP->rx_dataPacketsReSent = (afs_int32) rx_stats.dataPacketsReSent;
5674     a_perfP->rx_dataPacketsPushed = (afs_int32) rx_stats.dataPacketsPushed;
5675     a_perfP->rx_ignoreAckedPacket = (afs_int32) rx_stats.ignoreAckedPacket;
5676     a_perfP->rx_totalRtt_Sec = (afs_int32) rx_stats.totalRtt.sec;
5677     a_perfP->rx_totalRtt_Usec = (afs_int32) rx_stats.totalRtt.usec;
5678     a_perfP->rx_minRtt_Sec = (afs_int32) rx_stats.minRtt.sec;
5679     a_perfP->rx_minRtt_Usec = (afs_int32) rx_stats.minRtt.usec;
5680     a_perfP->rx_maxRtt_Sec = (afs_int32) rx_stats.maxRtt.sec;
5681     a_perfP->rx_maxRtt_Usec = (afs_int32) rx_stats.maxRtt.usec;
5682     a_perfP->rx_nRttSamples = (afs_int32) rx_stats.nRttSamples;
5683     a_perfP->rx_nServerConns = (afs_int32) rx_stats.nServerConns;
5684     a_perfP->rx_nClientConns = (afs_int32) rx_stats.nClientConns;
5685     a_perfP->rx_nPeerStructs = (afs_int32) rx_stats.nPeerStructs;
5686     a_perfP->rx_nCallStructs = (afs_int32) rx_stats.nCallStructs;
5687     a_perfP->rx_nFreeCallStructs = (afs_int32) rx_stats.nFreeCallStructs;
5688
5689     a_perfP->host_NumHostEntries = HTs;
5690     a_perfP->host_HostBlocks = HTBlocks;
5691     h_GetHostNetStats(&(a_perfP->host_NonDeletedHosts),
5692                       &(a_perfP->host_HostsInSameNetOrSubnet),
5693                       &(a_perfP->host_HostsInDiffSubnet),
5694                       &(a_perfP->host_HostsInDiffNetwork));
5695     a_perfP->host_NumClients = CEs;
5696     a_perfP->host_ClientBlocks = CEBlocks;
5697
5698     a_perfP->sysname_ID = afs_perfstats.sysname_ID;
5699     a_perfP->rx_nBusies = (afs_int32) rx_stats.nBusies;
5700     a_perfP->fs_nBusies = afs_perfstats.fs_nBusies;
5701 }                               /*FillPerfValues */
5702
5703
5704 /*------------------------------------------------------------------------
5705  * EXPORTED SRXAFS_GetXStats
5706  *
5707  * Description:
5708  *      Routine called by the server-side callback RPC interface to
5709  *      implement getting the given data collection from the extended
5710  *      File Server statistics.
5711  *
5712  * Arguments:
5713  *      a_call              : Ptr to Rx call on which this request came in.
5714  *      a_clientVersionNum  : Client version number.
5715  *      a_opCode            : Desired operation.
5716  *      a_serverVersionNumP : Ptr to version number to set.
5717  *      a_timeP             : Ptr to time value (seconds) to set.
5718  *      a_dataP             : Ptr to variable array structure to return
5719  *                            stuff in.
5720  *
5721  * Returns:
5722  *      0 (always).
5723  *
5724  * Environment:
5725  *      Nothing interesting.
5726  *
5727  * Side Effects:
5728  *      As advertised.
5729  *------------------------------------------------------------------------*/
5730
5731 afs_int32
5732 SRXAFS_GetXStats(struct rx_call *a_call, afs_int32 a_clientVersionNum,
5733                  afs_int32 a_collectionNumber, afs_int32 * a_srvVersionNumP,
5734                  afs_int32 * a_timeP, AFS_CollData * a_dataP)
5735 {                               /*SRXAFS_GetXStats */
5736
5737     register int code;          /*Return value */
5738     afs_int32 *dataBuffP;       /*Ptr to data to be returned */
5739     afs_int32 dataBytes;        /*Bytes in data buffer */
5740 #if FS_STATS_DETAILED
5741     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5742     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5743     struct timeval elapsedTime; /* Transfer time */
5744
5745     /*
5746      * Set our stats pointer, remember when the RPC operation started, and
5747      * tally the operation.
5748      */
5749     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETXSTATS]);
5750     FS_LOCK;
5751     (opP->numOps)++;
5752     FS_UNLOCK;
5753     TM_GetTimeOfDay(&opStartTime, 0);
5754 #endif /* FS_STATS_DETAILED */
5755
5756     /*
5757      * Record the time of day and the server version number.
5758      */
5759     *a_srvVersionNumP = AFS_XSTAT_VERSION;
5760     *a_timeP = FT_ApproxTime();
5761
5762     /*
5763      * Stuff the appropriate data in there (assume victory)
5764      */
5765     code = 0;
5766
5767     ViceLog(1,
5768             ("Received GetXStats call for collection %d\n",
5769              a_collectionNumber));
5770
5771 #if 0
5772     /*
5773      * We're not keeping stats, so just return successfully with
5774      * no data.
5775      */
5776     a_dataP->AFS_CollData_len = 0;
5777     a_dataP->AFS_CollData_val = NULL;
5778 #endif /* 0 */
5779
5780     switch (a_collectionNumber) {
5781     case AFS_XSTATSCOLL_CALL_INFO:
5782         /*
5783          * Pass back all the call-count-related data.
5784          *
5785          * >>> We are forced to allocate a separate area in which to
5786          * >>> put this stuff in by the RPC stub generator, since it
5787          * >>> will be freed at the tail end of the server stub code.
5788          */
5789 #if 0
5790         /*
5791          * I don't think call-level stats are being collected yet
5792          * for the File Server.
5793          */
5794         dataBytes = sizeof(struct afs_Stats);
5795         dataBuffP = (afs_int32 *) malloc(dataBytes);
5796         memcpy(dataBuffP, &afs_cmstats, dataBytes);
5797         a_dataP->AFS_CollData_len = dataBytes >> 2;
5798         a_dataP->AFS_CollData_val = dataBuffP;
5799 #else
5800         a_dataP->AFS_CollData_len = 0;
5801         a_dataP->AFS_CollData_val = NULL;
5802 #endif /* 0 */
5803         break;
5804
5805     case AFS_XSTATSCOLL_PERF_INFO:
5806         /*
5807          * Pass back all the regular performance-related data.
5808          *
5809          * >>> We are forced to allocate a separate area in which to
5810          * >>> put this stuff in by the RPC stub generator, since it
5811          * >>> will be freed at the tail end of the server stub code.
5812          */
5813
5814         afs_perfstats.numPerfCalls++;
5815         FillPerfValues(&afs_perfstats);
5816
5817         /*
5818          * Don't overwrite the spares at the end.
5819          */
5820
5821         dataBytes = sizeof(struct afs_PerfStats);
5822         dataBuffP = (afs_int32 *) malloc(dataBytes);
5823         memcpy(dataBuffP, &afs_perfstats, dataBytes);
5824         a_dataP->AFS_CollData_len = dataBytes >> 2;
5825         a_dataP->AFS_CollData_val = dataBuffP;
5826         break;
5827
5828     case AFS_XSTATSCOLL_FULL_PERF_INFO:
5829         /*
5830          * Pass back the full collection of performance-related data.
5831          * We have to stuff the basic, overall numbers in, but the
5832          * detailed numbers are kept in the structure already.
5833          *
5834          * >>> We are forced to allocate a separate area in which to
5835          * >>> put this stuff in by the RPC stub generator, since it
5836          * >>> will be freed at the tail end of the server stub code.
5837          */
5838
5839         afs_perfstats.numPerfCalls++;
5840 #if FS_STATS_DETAILED
5841         afs_FullPerfStats.overall.numPerfCalls = afs_perfstats.numPerfCalls;
5842         FillPerfValues(&afs_FullPerfStats.overall);
5843
5844         /*
5845          * Don't overwrite the spares at the end.
5846          */
5847
5848         dataBytes = sizeof(struct fs_stats_FullPerfStats);
5849         dataBuffP = (afs_int32 *) malloc(dataBytes);
5850         memcpy(dataBuffP, &afs_FullPerfStats, dataBytes);
5851         a_dataP->AFS_CollData_len = dataBytes >> 2;
5852         a_dataP->AFS_CollData_val = dataBuffP;
5853 #endif
5854         break;
5855
5856     case AFS_XSTATSCOLL_CBSTATS:
5857         afs_perfstats.numPerfCalls++;
5858
5859         dataBytes = sizeof(struct cbcounters);
5860         dataBuffP = (afs_int32 *) malloc(dataBytes);
5861         {
5862             extern struct cbcounters cbstuff;
5863             dataBuffP[0]=cbstuff.DeleteFiles;
5864             dataBuffP[1]=cbstuff.DeleteCallBacks;
5865             dataBuffP[2]=cbstuff.BreakCallBacks;
5866             dataBuffP[3]=cbstuff.AddCallBacks;
5867             dataBuffP[4]=cbstuff.GotSomeSpaces;
5868             dataBuffP[5]=cbstuff.DeleteAllCallBacks;
5869             dataBuffP[6]=cbstuff.nFEs;
5870             dataBuffP[7]=cbstuff.nCBs;
5871             dataBuffP[8]=cbstuff.nblks;
5872             dataBuffP[9]=cbstuff.CBsTimedOut;
5873             dataBuffP[10]=cbstuff.nbreakers;
5874             dataBuffP[11]=cbstuff.GSS1;
5875             dataBuffP[12]=cbstuff.GSS2;
5876             dataBuffP[13]=cbstuff.GSS3;
5877             dataBuffP[14]=cbstuff.GSS4;
5878             dataBuffP[15]=cbstuff.GSS5;
5879         }
5880
5881         a_dataP->AFS_CollData_len = dataBytes >> 2;
5882         a_dataP->AFS_CollData_val = dataBuffP;
5883         break;
5884
5885
5886     default:
5887         /*
5888          * Illegal collection number.
5889          */
5890         a_dataP->AFS_CollData_len = 0;
5891         a_dataP->AFS_CollData_val = NULL;
5892         code = 1;
5893     }                           /*Switch on collection number */
5894
5895 #if FS_STATS_DETAILED
5896     TM_GetTimeOfDay(&opStopTime, 0);
5897     if (code == 0) {
5898         FS_LOCK;
5899         (opP->numSuccesses)++;
5900         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5901         fs_stats_AddTo((opP->sumTime), elapsedTime);
5902         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5903         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5904             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5905         }
5906         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5907             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5908         }
5909         FS_UNLOCK;
5910     }
5911 #endif /* FS_STATS_DETAILED */
5912
5913     return (code);
5914
5915 }                               /*SRXAFS_GetXStats */
5916
5917
5918 static afs_int32
5919 common_GiveUpCallBacks(struct rx_call *acall, struct AFSCBFids *FidArray,
5920                        struct AFSCBs *CallBackArray)
5921 {
5922     afs_int32 errorCode = 0;
5923     register int i;
5924     struct client *client = 0;
5925     struct rx_connection *tcon;
5926     struct host *thost;
5927 #if FS_STATS_DETAILED
5928     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5929     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5930     struct timeval elapsedTime; /* Transfer time */
5931
5932     /*
5933      * Set our stats pointer, remember when the RPC operation started, and
5934      * tally the operation.
5935      */
5936     opP =
5937         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GIVEUPCALLBACKS]);
5938     FS_LOCK;
5939     (opP->numOps)++;
5940     FS_UNLOCK;
5941     TM_GetTimeOfDay(&opStartTime, 0);
5942 #endif /* FS_STATS_DETAILED */
5943
5944     if (FidArray)
5945         ViceLog(1,
5946                 ("SAFS_GiveUpCallBacks (Noffids=%d)\n",
5947                  FidArray->AFSCBFids_len));
5948
5949     FS_LOCK;
5950     AFSCallStats.GiveUpCallBacks++, AFSCallStats.TotalCalls++;
5951     FS_UNLOCK;
5952     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5953         goto Bad_GiveUpCallBacks;
5954
5955     if (!FidArray && !CallBackArray) {
5956         ViceLog(1,
5957                 ("SAFS_GiveUpAllCallBacks: host=%x\n",
5958                  (tcon->peer ? tcon->peer->host : 0)));
5959         errorCode = GetClient(tcon, &client);
5960         if (!errorCode) {
5961             DeleteAllCallBacks_r(client->host, 1);
5962             PutClient(&client);
5963         }
5964     } else {
5965         if (FidArray->AFSCBFids_len < CallBackArray->AFSCBs_len) {
5966             ViceLog(0,
5967                     ("GiveUpCallBacks: #Fids %d < #CallBacks %d, host=%x\n",
5968                      FidArray->AFSCBFids_len, CallBackArray->AFSCBs_len,
5969                      (tcon->peer ? tcon->peer->host : 0)));
5970             errorCode = EINVAL;
5971             goto Bad_GiveUpCallBacks;
5972         }
5973
5974         errorCode = GetClient(tcon, &client);
5975         if (!errorCode) {
5976             for (i = 0; i < FidArray->AFSCBFids_len; i++) {
5977                 register struct AFSFid *fid = &(FidArray->AFSCBFids_val[i]);
5978                 DeleteCallBack(client->host, fid);
5979             }
5980             PutClient(&client);
5981         }
5982     }
5983
5984   Bad_GiveUpCallBacks:
5985     errorCode = CallPostamble(tcon, errorCode, thost);
5986
5987 #if FS_STATS_DETAILED
5988     TM_GetTimeOfDay(&opStopTime, 0);
5989     if (errorCode == 0) {
5990         FS_LOCK;
5991         (opP->numSuccesses)++;
5992         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5993         fs_stats_AddTo((opP->sumTime), elapsedTime);
5994         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5995         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5996             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5997         }
5998         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5999             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6000         }
6001         FS_UNLOCK;
6002     }
6003 #endif /* FS_STATS_DETAILED */
6004     return errorCode;
6005
6006 }                               /*common_GiveUpCallBacks */
6007
6008
6009 afs_int32
6010 SRXAFS_GiveUpCallBacks(struct rx_call * acall, struct AFSCBFids * FidArray,
6011                        struct AFSCBs * CallBackArray)
6012 {
6013     return common_GiveUpCallBacks(acall, FidArray, CallBackArray);
6014 }                               /*SRXAFS_GiveUpCallBacks */
6015
6016 afs_int32
6017 SRXAFS_GiveUpAllCallBacks(struct rx_call * acall)
6018 {
6019     return common_GiveUpCallBacks(acall, 0, 0);
6020 }                               /*SRXAFS_GiveUpAllCallBacks */
6021
6022
6023 afs_int32
6024 SRXAFS_NGetVolumeInfo(struct rx_call * acall, char *avolid,
6025                       struct AFSVolumeInfo * avolinfo)
6026 {
6027     return (VNOVOL);            /* XXX Obsolete routine XXX */
6028
6029 }                               /*SRXAFS_NGetVolumeInfo */
6030
6031
6032 /*
6033  * Dummy routine. Should never be called (the cache manager should only 
6034  * invoke this interface when communicating with a AFS/DFS Protocol
6035  * Translator).
6036  */
6037 afs_int32
6038 SRXAFS_Lookup(struct rx_call * call_p, struct AFSFid * afs_dfid_p,
6039               char *afs_name_p, struct AFSFid * afs_fid_p,
6040               struct AFSFetchStatus * afs_status_p,
6041               struct AFSFetchStatus * afs_dir_status_p,
6042               struct AFSCallBack * afs_callback_p,
6043               struct AFSVolSync * afs_sync_p)
6044 {
6045     return EINVAL;
6046 }
6047
6048
6049 afs_int32
6050 SRXAFS_GetCapabilities(struct rx_call * acall, Capabilities * capabilities)
6051 {
6052     afs_int32 code;
6053     struct rx_connection *tcon;
6054     struct host *thost;
6055     afs_int32 *dataBuffP;
6056     afs_int32 dataBytes;
6057
6058     FS_LOCK;
6059     AFSCallStats.GetCapabilities++, AFSCallStats.TotalCalls++;
6060     afs_FullPerfStats.overall.fs_nGetCaps++;
6061     FS_UNLOCK;
6062     ViceLog(2, ("SAFS_GetCapabilties\n"));
6063
6064     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
6065         goto Bad_GetCaps;
6066
6067     dataBytes = 1 * sizeof(afs_int32);
6068     dataBuffP = (afs_int32 *) malloc(dataBytes);
6069     dataBuffP[0] = VICED_CAPABILITY_ERRORTRANS | VICED_CAPABILITY_WRITELOCKACL;
6070 #if defined(AFS_64BIT_ENV) && defined(AFS_LARGEFILE_ENV)
6071     dataBuffP[0] |= VICED_CAPABILITY_64BITFILES;
6072 #endif
6073     if (saneacls)
6074         dataBuffP[0] |= VICED_CAPABILITY_SANEACLS;
6075
6076     capabilities->Capabilities_len = dataBytes / sizeof(afs_int32);
6077     capabilities->Capabilities_val = dataBuffP;
6078
6079   Bad_GetCaps:
6080     code = CallPostamble(tcon, code, thost);
6081
6082
6083     return 0;
6084 }
6085
6086 afs_int32
6087 SRXAFS_FlushCPS(struct rx_call * acall, struct ViceIds * vids,
6088                 struct IPAddrs * addrs, afs_int32 spare1, afs_int32 * spare2,
6089                 afs_int32 * spare3)
6090 {
6091     int i;
6092     afs_int32 nids, naddrs;
6093     afs_int32 *vd, *addr;
6094     int errorCode = 0;          /* return code to caller */
6095     struct client *client = 0;
6096     struct rx_connection *tcon = rx_ConnectionOf(acall);
6097
6098     ViceLog(1, ("SRXAFS_FlushCPS\n"));
6099     FS_LOCK;
6100     AFSCallStats.TotalCalls++;
6101     FS_UNLOCK;
6102     nids = vids->ViceIds_len;   /* # of users in here */
6103     naddrs = addrs->IPAddrs_len;        /* # of hosts in here */
6104     if (nids < 0 || naddrs < 0) {
6105         errorCode = EINVAL;
6106         goto Bad_FlushCPS;
6107     }
6108
6109     vd = vids->ViceIds_val;
6110     for (i = 0; i < nids; i++, vd++) {
6111         if (!*vd)
6112             continue;
6113         client = h_ID2Client(*vd);      /* returns write locked and refCounted, or NULL */
6114         if (!client)
6115             continue;
6116
6117         client->prfail = 2;     /* Means re-eval client's cps */
6118 #ifdef  notdef
6119         if (client->tcon) {
6120             rx_SetRock(((struct rx_connection *)client->tcon), 0);
6121         }
6122 #endif
6123         if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val) {
6124             free(client->CPS.prlist_val);
6125             client->CPS.prlist_val = NULL;
6126             client->CPS.prlist_len = 0;
6127         }
6128         ReleaseWriteLock(&client->lock);
6129         PutClient(&client);
6130     }
6131
6132     addr = addrs->IPAddrs_val;
6133     for (i = 0; i < naddrs; i++, addr++) {
6134         if (*addr)
6135             h_flushhostcps(*addr, htons(7001));
6136     }
6137
6138   Bad_FlushCPS:
6139     ViceLog(2, ("SAFS_FlushCPS  returns %d\n", errorCode));
6140     return errorCode;
6141 }                               /*SRXAFS_FlushCPS */
6142
6143 /* worthless hack to let CS keep running ancient software */
6144 static int
6145 afs_vtoi(register char *aname)
6146 {
6147     register afs_int32 temp;
6148     register int tc;
6149
6150     temp = 0;
6151     while ((tc = *aname++)) {
6152         if (tc > '9' || tc < '0')
6153             return 0;           /* invalid name */
6154         temp *= 10;
6155         temp += tc - '0';
6156     }
6157     return temp;
6158 }
6159
6160 /*
6161  * may get name or #, but must handle all weird cases (recognize readonly
6162  * or backup volumes by name or #
6163  */
6164 static afs_int32
6165 CopyVolumeEntry(char *aname, register struct vldbentry *ave,
6166                 register struct VolumeInfo *av)
6167 {
6168     register int i, j, vol;
6169     afs_int32 mask, whichType;
6170     afs_uint32 *serverHost, *typePtr;
6171
6172     /* figure out what type we want if by name */
6173     i = strlen(aname);
6174     if (i >= 8 && strcmp(aname + i - 7, ".backup") == 0)
6175         whichType = BACKVOL;
6176     else if (i >= 10 && strcmp(aname + i - 9, ".readonly") == 0)
6177         whichType = ROVOL;
6178     else
6179         whichType = RWVOL;
6180
6181     vol = afs_vtoi(aname);
6182     if (vol == 0)
6183         vol = ave->volumeId[whichType];
6184
6185     /*
6186      * Now vol has volume # we're interested in.  Next, figure out the type
6187      * of the volume by looking finding it in the vldb entry
6188      */
6189     if ((ave->flags & VLF_RWEXISTS) && vol == ave->volumeId[RWVOL]) {
6190         mask = VLSF_RWVOL;
6191         whichType = RWVOL;
6192     } else if ((ave->flags & VLF_ROEXISTS) && vol == ave->volumeId[ROVOL]) {
6193         mask = VLSF_ROVOL;
6194         whichType = ROVOL;
6195     } else if ((ave->flags & VLF_BACKEXISTS) && vol == ave->volumeId[BACKVOL]) {
6196         mask = VLSF_RWVOL;      /* backup always is on the same volume as parent */
6197         whichType = BACKVOL;
6198     } else
6199         return EINVAL;          /* error: can't find volume in vldb entry */
6200
6201     typePtr = &av->Type0;
6202     serverHost = &av->Server0;
6203     av->Vid = vol;
6204     av->Type = whichType;
6205     av->Type0 = av->Type1 = av->Type2 = av->Type3 = av->Type4 = 0;
6206     if (ave->flags & VLF_RWEXISTS)
6207         typePtr[RWVOL] = ave->volumeId[RWVOL];
6208     if (ave->flags & VLF_ROEXISTS)
6209         typePtr[ROVOL] = ave->volumeId[ROVOL];
6210     if (ave->flags & VLF_BACKEXISTS)
6211         typePtr[BACKVOL] = ave->volumeId[BACKVOL];
6212
6213     for (i = 0, j = 0; i < ave->nServers; i++) {
6214         if ((ave->serverFlags[i] & mask) == 0)
6215             continue;           /* wrong volume */
6216         serverHost[j] = ave->serverNumber[i];
6217         j++;
6218     }
6219     av->ServerCount = j;
6220     if (j < 8)
6221         serverHost[j++] = 0;    /* bogus 8, but compat only now */
6222     return 0;
6223 }
6224
6225 static afs_int32
6226 TryLocalVLServer(char *avolid, struct VolumeInfo *avolinfo)
6227 {
6228     static struct rx_connection *vlConn = 0;
6229     static int down = 0;
6230     static afs_int32 lastDownTime = 0;
6231     struct vldbentry tve;
6232     struct rx_securityClass *vlSec;
6233     register afs_int32 code;
6234
6235     if (!vlConn) {
6236         vlSec = rxnull_NewClientSecurityObject();
6237         vlConn =
6238             rx_NewConnection(htonl(0x7f000001), htons(7003), 52, vlSec, 0);
6239         rx_SetConnDeadTime(vlConn, 15); /* don't wait long */
6240     }
6241     if (down && (FT_ApproxTime() < lastDownTime + 180)) {
6242         return 1;               /* failure */
6243     }
6244
6245     code = VL_GetEntryByNameO(vlConn, avolid, &tve);
6246     if (code >= 0)
6247         down = 0;               /* call worked */
6248     if (code) {
6249         if (code < 0) {
6250             lastDownTime = FT_ApproxTime();     /* last time we tried an RPC */
6251             down = 1;
6252         }
6253         return code;
6254     }
6255
6256     /* otherwise convert to old format vldb entry */
6257     code = CopyVolumeEntry(avolid, &tve, avolinfo);
6258     return code;
6259 }
6260
6261
6262
6263
6264
6265
6266 afs_int32
6267 SRXAFS_GetVolumeInfo(struct rx_call * acall, char *avolid,
6268                      struct VolumeInfo * avolinfo)
6269 {
6270     afs_int32 code;
6271     struct rx_connection *tcon;
6272     struct host *thost;
6273 #if FS_STATS_DETAILED
6274     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6275     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6276     struct timeval elapsedTime; /* Transfer time */
6277
6278     /*
6279      * Set our stats pointer, remember when the RPC operation started, and
6280      * tally the operation.
6281      */
6282     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETVOLUMEINFO]);
6283     FS_LOCK;
6284     (opP->numOps)++;
6285     FS_UNLOCK;
6286     TM_GetTimeOfDay(&opStartTime, 0);
6287 #endif /* FS_STATS_DETAILED */
6288     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6289         goto Bad_GetVolumeInfo;
6290
6291     FS_LOCK;
6292     AFSCallStats.GetVolumeInfo++, AFSCallStats.TotalCalls++;
6293     FS_UNLOCK;
6294     code = TryLocalVLServer(avolid, avolinfo);
6295     ViceLog(1,
6296             ("SAFS_GetVolumeInfo returns %d, Volume %u, type %x, servers %x %x %x %x...\n",
6297              code, avolinfo->Vid, avolinfo->Type, avolinfo->Server0,
6298              avolinfo->Server1, avolinfo->Server2, avolinfo->Server3));
6299     avolinfo->Type4 = 0xabcd9999;       /* tell us to try new vldb */
6300
6301   Bad_GetVolumeInfo:
6302     code = CallPostamble(tcon, code, thost);
6303
6304 #if FS_STATS_DETAILED
6305     TM_GetTimeOfDay(&opStopTime, 0);
6306     if (code == 0) {
6307         FS_LOCK;
6308         (opP->numSuccesses)++;
6309         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6310         fs_stats_AddTo((opP->sumTime), elapsedTime);
6311         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6312         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6313             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6314         }
6315         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6316             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6317         }
6318         FS_UNLOCK;
6319     }
6320 #endif /* FS_STATS_DETAILED */
6321
6322     return code;
6323
6324 }                               /*SRXAFS_GetVolumeInfo */
6325
6326
6327 afs_int32
6328 SRXAFS_GetVolumeStatus(struct rx_call * acall, afs_int32 avolid,
6329                        AFSFetchVolumeStatus * FetchVolStatus, char **Name,
6330                        char **OfflineMsg, char **Motd)
6331 {
6332     Vnode *targetptr = 0;       /* vnode of the new file */
6333     Vnode *parentwhentargetnotdir = 0;  /* vnode of parent */
6334     int errorCode = 0;          /* error code */
6335     Volume *volptr = 0;         /* pointer to the volume header */
6336     struct client *client = 0;  /* pointer to client entry */
6337     afs_int32 rights, anyrights;        /* rights for this and any user */
6338     AFSFid dummyFid;
6339     struct rx_connection *tcon;
6340     struct host *thost;
6341     struct client *t_client = NULL;     /* tmp ptr to client data */
6342 #if FS_STATS_DETAILED
6343     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6344     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6345     struct timeval elapsedTime; /* Transfer time */
6346
6347     /*
6348      * Set our stats pointer, remember when the RPC operation started, and
6349      * tally the operation.
6350      */
6351     opP =
6352         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETVOLUMESTATUS]);
6353     FS_LOCK;
6354     (opP->numOps)++;
6355     FS_UNLOCK;
6356     TM_GetTimeOfDay(&opStartTime, 0);
6357 #endif /* FS_STATS_DETAILED */
6358
6359     ViceLog(1, ("SAFS_GetVolumeStatus for volume %u\n", avolid));
6360     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6361         goto Bad_GetVolumeStatus;
6362
6363     FS_LOCK;
6364     AFSCallStats.GetVolumeStatus++, AFSCallStats.TotalCalls++;
6365     FS_UNLOCK;
6366     if (avolid == 0) {
6367         errorCode = EINVAL;
6368         goto Bad_GetVolumeStatus;
6369     }
6370     dummyFid.Volume = avolid, dummyFid.Vnode =
6371         (afs_int32) ROOTVNODE, dummyFid.Unique = 1;
6372
6373     if ((errorCode =
6374          GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr, MustBeDIR,
6375                           &parentwhentargetnotdir, &client, READ_LOCK,
6376                           &rights, &anyrights)))
6377         goto Bad_GetVolumeStatus;
6378
6379     if ((VanillaUser(client)) && (!(rights & PRSFS_READ))) {
6380         errorCode = EACCES;
6381         goto Bad_GetVolumeStatus;
6382     }
6383     (void)RXGetVolumeStatus(FetchVolStatus, Name, OfflineMsg, Motd, volptr);
6384
6385   Bad_GetVolumeStatus:
6386     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
6387                            volptr, &client);
6388     ViceLog(2, ("SAFS_GetVolumeStatus returns %d\n", errorCode));
6389     /* next is to guarantee out strings exist for stub */
6390     if (*Name == 0) {
6391         *Name = (char *)malloc(1);
6392         **Name = 0;
6393     }
6394     if (*Motd == 0) {
6395         *Motd = (char *)malloc(1);
6396         **Motd = 0;
6397     }
6398     if (*OfflineMsg == 0) {
6399         *OfflineMsg = (char *)malloc(1);
6400         **OfflineMsg = 0;
6401     }
6402     errorCode = CallPostamble(tcon, errorCode, thost);
6403
6404     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
6405
6406 #if FS_STATS_DETAILED
6407     TM_GetTimeOfDay(&opStopTime, 0);
6408     if (errorCode == 0) {
6409         FS_LOCK;
6410         (opP->numSuccesses)++;
6411         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6412         fs_stats_AddTo((opP->sumTime), elapsedTime);
6413         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6414         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6415             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6416         }
6417         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6418             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6419         }
6420         FS_UNLOCK;
6421     }
6422 #endif /* FS_STATS_DETAILED */
6423
6424     osi_auditU(acall, GetVolumeStatusEvent, errorCode, 
6425                AUD_ID, t_client ? t_client->ViceId : 0,
6426                AUD_LONG, avolid, AUD_STR, *Name, AUD_END);
6427     return (errorCode);
6428
6429 }                               /*SRXAFS_GetVolumeStatus */
6430
6431
6432 afs_int32
6433 SRXAFS_SetVolumeStatus(struct rx_call * acall, afs_int32 avolid,
6434                        AFSStoreVolumeStatus * StoreVolStatus, char *Name,
6435                        char *OfflineMsg, char *Motd)
6436 {
6437     Vnode *targetptr = 0;       /* vnode of the new file */
6438     Vnode *parentwhentargetnotdir = 0;  /* vnode of parent */
6439     int errorCode = 0;          /* error code */
6440     Volume *volptr = 0;         /* pointer to the volume header */
6441     struct client *client = 0;  /* pointer to client entry */
6442     afs_int32 rights, anyrights;        /* rights for this and any user */
6443     AFSFid dummyFid;
6444     struct rx_connection *tcon = rx_ConnectionOf(acall);
6445     struct host *thost;
6446     struct client *t_client = NULL;     /* tmp ptr to client data */
6447 #if FS_STATS_DETAILED
6448     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6449     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6450     struct timeval elapsedTime; /* Transfer time */
6451
6452     /*
6453      * Set our stats pointer, remember when the RPC operation started, and
6454      * tally the operation.
6455      */
6456     opP =
6457         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SETVOLUMESTATUS]);
6458     FS_LOCK;
6459     (opP->numOps)++;
6460     FS_UNLOCK;
6461     TM_GetTimeOfDay(&opStartTime, 0);
6462 #endif /* FS_STATS_DETAILED */
6463
6464     ViceLog(1, ("SAFS_SetVolumeStatus for volume %u\n", avolid));
6465     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6466         goto Bad_SetVolumeStatus;
6467
6468     FS_LOCK;
6469     AFSCallStats.SetVolumeStatus++, AFSCallStats.TotalCalls++;
6470     FS_UNLOCK;
6471     if (avolid == 0) {
6472         errorCode = EINVAL;
6473         goto Bad_SetVolumeStatus;
6474     }
6475     dummyFid.Volume = avolid, dummyFid.Vnode =
6476         (afs_int32) ROOTVNODE, dummyFid.Unique = 1;
6477
6478     if ((errorCode =
6479          GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr, MustBeDIR,
6480                           &parentwhentargetnotdir, &client, READ_LOCK,
6481                           &rights, &anyrights)))
6482         goto Bad_SetVolumeStatus;
6483
6484     if (readonlyServer) {
6485         errorCode = VREADONLY;
6486         goto Bad_SetVolumeStatus;
6487     }
6488     if (VanillaUser(client)) {
6489         errorCode = EACCES;
6490         goto Bad_SetVolumeStatus;
6491     }
6492
6493     errorCode =
6494         RXUpdate_VolumeStatus(volptr, StoreVolStatus, Name, OfflineMsg, Motd);
6495
6496   Bad_SetVolumeStatus:
6497     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
6498                      volptr, &client);
6499     ViceLog(2, ("SAFS_SetVolumeStatus returns %d\n", errorCode));
6500     errorCode = CallPostamble(tcon, errorCode, thost);
6501
6502     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
6503
6504 #if FS_STATS_DETAILED
6505     TM_GetTimeOfDay(&opStopTime, 0);
6506     if (errorCode == 0) {
6507         FS_LOCK;
6508         (opP->numSuccesses)++;
6509         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6510         fs_stats_AddTo((opP->sumTime), elapsedTime);
6511         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6512         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6513             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6514         }
6515         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6516             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6517         }
6518         FS_UNLOCK;
6519     }
6520 #endif /* FS_STATS_DETAILED */
6521
6522     osi_auditU(acall, SetVolumeStatusEvent, errorCode, 
6523                AUD_ID, t_client ? t_client->ViceId : 0,
6524                AUD_LONG, avolid, AUD_STR, Name, AUD_END);
6525     return (errorCode);
6526 }                               /*SRXAFS_SetVolumeStatus */
6527
6528 #define DEFAULTVOLUME   "root.afs"
6529
6530 afs_int32
6531 SRXAFS_GetRootVolume(struct rx_call * acall, char **VolumeName)
6532 {
6533 #ifdef notdef
6534     int fd;
6535     int len;
6536     char *temp;
6537     struct rx_connection *tcon;
6538     struct host *thost;
6539 #endif
6540     int errorCode = 0;
6541 #if FS_STATS_DETAILED
6542     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6543     struct timeval opStartTime; /* Start time for RPC op */
6544 #ifdef notdef
6545     struct timeval opStopTime;
6546     struct timeval elapsedTime; /* Transfer time */
6547 #endif
6548
6549     /*
6550      * Set our stats pointer, remember when the RPC operation started, and
6551      * tally the operation.
6552      */
6553     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETROOTVOLUME]);
6554     FS_LOCK;
6555     (opP->numOps)++;
6556     FS_UNLOCK;
6557     TM_GetTimeOfDay(&opStartTime, 0);
6558 #endif /* FS_STATS_DETAILED */
6559
6560     return FSERR_EOPNOTSUPP;
6561
6562 #ifdef  notdef
6563     if (errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost))
6564         goto Bad_GetRootVolume;
6565     FS_LOCK;
6566     AFSCallStats.GetRootVolume++, AFSCallStats.TotalCalls++;
6567     FS_UNLOCK;
6568     temp = malloc(256);
6569     fd = afs_open(AFSDIR_SERVER_ROOTVOL_FILEPATH, O_RDONLY, 0666);
6570     if (fd <= 0)
6571         strcpy(temp, DEFAULTVOLUME);
6572     else {
6573 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6574         lockf(fd, F_LOCK, 0);
6575 #else
6576         flock(fd, LOCK_EX);
6577 #endif
6578         len = read(fd, temp, 256);
6579 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6580         lockf(fd, F_ULOCK, 0);
6581 #else
6582         flock(fd, LOCK_UN);
6583 #endif
6584         close(fd);
6585         if (temp[len - 1] == '\n')
6586             len--;
6587         temp[len] = '\0';
6588     }
6589     *VolumeName = temp;         /* freed by rx server-side stub */
6590
6591   Bad_GetRootVolume:
6592     errorCode = CallPostamble(tcon, errorCode, thost);
6593
6594 #if FS_STATS_DETAILED
6595     TM_GetTimeOfDay(&opStopTime, 0);
6596     if (errorCode == 0) {
6597         FS_LOCK;
6598         (opP->numSuccesses)++;
6599         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6600         fs_stats_AddTo((opP->sumTime), elapsedTime);
6601         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6602         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6603             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6604         }
6605         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6606             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6607         }
6608         FS_UNLOCK;
6609     }
6610 #endif /* FS_STATS_DETAILED */
6611
6612     return (errorCode);
6613 #endif /* notdef */
6614
6615 }                               /*SRXAFS_GetRootVolume */
6616
6617
6618 /* still works because a struct CBS is the same as a struct AFSOpaque */
6619 afs_int32
6620 SRXAFS_CheckToken(struct rx_call * acall, afs_int32 AfsId,
6621                   struct AFSOpaque * Token)
6622 {
6623     afs_int32 code;
6624     struct rx_connection *tcon;
6625     struct host *thost;
6626 #if FS_STATS_DETAILED
6627     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6628     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6629     struct timeval elapsedTime; /* Transfer time */
6630
6631     /*
6632      * Set our stats pointer, remember when the RPC operation started, and
6633      * tally the operation.
6634      */
6635     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_CHECKTOKEN]);
6636     FS_LOCK;
6637     (opP->numOps)++;
6638     FS_UNLOCK;
6639     TM_GetTimeOfDay(&opStartTime, 0);
6640 #endif /* FS_STATS_DETAILED */
6641
6642     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6643         goto Bad_CheckToken;
6644
6645     code = FSERR_ECONNREFUSED;
6646
6647   Bad_CheckToken:
6648     code = CallPostamble(tcon, code, thost);
6649
6650 #if FS_STATS_DETAILED
6651     TM_GetTimeOfDay(&opStopTime, 0);
6652     if (code == 0) {
6653         FS_LOCK;
6654         (opP->numSuccesses)++;
6655         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6656         fs_stats_AddTo((opP->sumTime), elapsedTime);
6657         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6658         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6659             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6660         }
6661         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6662             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6663         }
6664         FS_UNLOCK;
6665     }
6666 #endif /* FS_STATS_DETAILED */
6667
6668     return code;
6669
6670 }                               /*SRXAFS_CheckToken */
6671
6672 afs_int32
6673 SRXAFS_GetTime(struct rx_call * acall, afs_uint32 * Seconds,
6674                afs_uint32 * USeconds)
6675 {
6676     afs_int32 code;
6677     struct rx_connection *tcon;
6678     struct host *thost;
6679     struct timeval tpl;
6680 #if FS_STATS_DETAILED
6681     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6682     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6683     struct timeval elapsedTime; /* Transfer time */
6684
6685     /*
6686      * Set our stats pointer, remember when the RPC operation started, and
6687      * tally the operation.
6688      */
6689     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETTIME]);
6690     FS_LOCK;
6691     (opP->numOps)++;
6692     FS_UNLOCK;
6693     TM_GetTimeOfDay(&opStartTime, 0);
6694 #endif /* FS_STATS_DETAILED */
6695
6696     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
6697         goto Bad_GetTime;
6698
6699     FS_LOCK;
6700     AFSCallStats.GetTime++, AFSCallStats.TotalCalls++;
6701     FS_UNLOCK;
6702     TM_GetTimeOfDay(&tpl, 0);
6703     *Seconds = tpl.tv_sec;
6704     *USeconds = tpl.tv_usec;
6705
6706     ViceLog(2, ("SAFS_GetTime returns %u, %u\n", *Seconds, *USeconds));
6707
6708   Bad_GetTime:
6709     code = CallPostamble(tcon, code, thost);
6710
6711 #if FS_STATS_DETAILED
6712     TM_GetTimeOfDay(&opStopTime, 0);
6713     fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6714     if (code == 0) {
6715         FS_LOCK;
6716         (opP->numSuccesses)++;
6717         fs_stats_AddTo((opP->sumTime), elapsedTime);
6718         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6719         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6720             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6721         }
6722         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6723             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6724         }
6725         FS_UNLOCK;
6726     }
6727 #endif /* FS_STATS_DETAILED */
6728
6729     return code;
6730
6731 }                               /*SRXAFS_GetTime */
6732
6733
6734 /*
6735  * FetchData_RXStyle
6736  *
6737  * Purpose:
6738  *      Implement a client's data fetch using Rx.
6739  *
6740  * Arguments:
6741  *      volptr          : Ptr to the given volume's info.
6742  *      targetptr       : Pointer to the vnode involved.
6743  *      Call            : Ptr to the Rx call involved.
6744  *      Pos             : Offset within the file.
6745  *      Len             : Length in bytes to read; this value is bogus!
6746  * if FS_STATS_DETAILED
6747  *      a_bytesToFetchP : Set to the number of bytes to be fetched from
6748  *                        the File Server.
6749  *      a_bytesFetchedP : Set to the actual number of bytes fetched from
6750  *                        the File Server.
6751  * endif
6752  */
6753
6754 afs_int32
6755 FetchData_RXStyle(Volume * volptr, Vnode * targetptr,
6756                   register struct rx_call * Call, afs_sfsize_t Pos,
6757                   afs_sfsize_t Len, afs_int32 Int64Mode,
6758 #if FS_STATS_DETAILED
6759                   afs_sfsize_t * a_bytesToFetchP,
6760                   afs_sfsize_t * a_bytesFetchedP
6761 #endif                          /* FS_STATS_DETAILED */
6762     )
6763 {
6764     struct timeval StartTime, StopTime; /* used to calculate file  transfer rates */
6765     int errorCode = 0;          /* Returned error code to caller */
6766     IHandle_t *ihP;
6767     FdHandle_t *fdP;
6768 #ifdef AFS_NT40_ENV
6769     register char *tbuffer;
6770 #else /* AFS_NT40_ENV */
6771     struct iovec tiov[RX_MAXIOVECS];
6772     int tnio;
6773 #endif /* AFS_NT40_ENV */
6774     afs_sfsize_t tlen;
6775     afs_int32 optSize;
6776
6777 #if FS_STATS_DETAILED
6778     /*
6779      * Initialize the byte count arguments.
6780      */
6781     (*a_bytesToFetchP) = 0;
6782     (*a_bytesFetchedP) = 0;
6783 #endif /* FS_STATS_DETAILED */
6784
6785
6786     ViceLog(25,
6787             ("FetchData_RXStyle: Pos %llu, Len %llu\n", (afs_uintmax_t) Pos,
6788              (afs_uintmax_t) Len));
6789
6790     if (!VN_GET_INO(targetptr)) {
6791         afs_int32 zero = htonl(0);
6792         /*
6793          * This is used for newly created files; we simply send 0 bytes
6794          * back to make the cache manager happy...
6795          */
6796         if (Int64Mode)
6797             rx_Write(Call, (char *)&zero, sizeof(afs_int32));   /* send 0-length  */
6798         rx_Write(Call, (char *)&zero, sizeof(afs_int32));       /* send 0-length  */
6799         return (0);
6800     }
6801     TM_GetTimeOfDay(&StartTime, 0);
6802     ihP = targetptr->handle;
6803     fdP = IH_OPEN(ihP);
6804     if (fdP == NULL) {
6805         VTakeOffline(volptr);
6806         return EIO;
6807     }
6808     optSize = sendBufSize;
6809     tlen = FDH_SIZE(fdP);
6810     ViceLog(25,
6811             ("FetchData_RXStyle: file size %llu\n", (afs_uintmax_t) tlen));
6812     if (tlen < 0) {
6813         FDH_CLOSE(fdP);
6814         VTakeOffline(volptr);
6815         return EIO;
6816     }
6817     if (Pos > tlen) {
6818         Len = 0;
6819     }
6820
6821     if (Pos + Len > tlen)
6822         Len = tlen - Pos;       /* get length we should send */
6823     (void)FDH_SEEK(fdP, Pos, 0);
6824     {
6825         afs_int32 high, low;
6826         SplitOffsetOrSize(Len, high, low);
6827         assert(Int64Mode || (Len >= 0 && high == 0) || Len < 0);
6828         if (Int64Mode) {
6829             high = htonl(high);
6830             rx_Write(Call, (char *)&high, sizeof(afs_int32));   /* High order bits */
6831         }
6832         low = htonl(low);
6833         rx_Write(Call, (char *)&low, sizeof(afs_int32));        /* send length on fetch */
6834     }
6835 #if FS_STATS_DETAILED
6836     (*a_bytesToFetchP) = Len;
6837 #endif /* FS_STATS_DETAILED */
6838 #ifdef AFS_NT40_ENV
6839     tbuffer = AllocSendBuffer();
6840 #endif /* AFS_NT40_ENV */
6841     while (Len > 0) {
6842         int wlen;
6843         if (Len > optSize)
6844             wlen = optSize;
6845         else
6846             wlen = (int)Len;
6847 #ifdef AFS_NT40_ENV
6848         errorCode = FDH_READ(fdP, tbuffer, wlen);
6849         if (errorCode != wlen) {
6850             FDH_CLOSE(fdP);
6851             FreeSendBuffer((struct afs_buffer *)tbuffer);
6852             VTakeOffline(volptr);
6853             return EIO;
6854         }
6855         errorCode = rx_Write(Call, tbuffer, wlen);
6856 #else /* AFS_NT40_ENV */
6857         errorCode = rx_WritevAlloc(Call, tiov, &tnio, RX_MAXIOVECS, wlen);
6858         if (errorCode <= 0) {
6859             FDH_CLOSE(fdP);
6860             return EIO;
6861         }
6862         wlen = errorCode;
6863         errorCode = FDH_READV(fdP, tiov, tnio);
6864         if (errorCode != wlen) {
6865             FDH_CLOSE(fdP);
6866             VTakeOffline(volptr);
6867             return EIO;
6868         }
6869         errorCode = rx_Writev(Call, tiov, tnio, wlen);
6870 #endif /* AFS_NT40_ENV */
6871 #if FS_STATS_DETAILED
6872         /*
6873          * Bump the number of bytes actually sent by the number from this
6874          * latest iteration
6875          */
6876         (*a_bytesFetchedP) += errorCode;
6877 #endif /* FS_STATS_DETAILED */
6878         if (errorCode != wlen) {
6879             FDH_CLOSE(fdP);
6880 #ifdef AFS_NT40_ENV
6881             FreeSendBuffer((struct afs_buffer *)tbuffer);
6882 #endif /* AFS_NT40_ENV */
6883             return -31;
6884         }
6885         Len -= wlen;
6886     }
6887 #ifdef AFS_NT40_ENV
6888     FreeSendBuffer((struct afs_buffer *)tbuffer);
6889 #endif /* AFS_NT40_ENV */
6890     FDH_CLOSE(fdP);
6891     TM_GetTimeOfDay(&StopTime, 0);
6892
6893     /* Adjust all Fetch Data related stats */
6894     FS_LOCK;
6895     if (AFSCallStats.TotalFetchedBytes > 2000000000)    /* Reset if over 2 billion */
6896         AFSCallStats.TotalFetchedBytes = AFSCallStats.AccumFetchTime = 0;
6897     AFSCallStats.AccumFetchTime +=
6898         ((StopTime.tv_sec - StartTime.tv_sec) * 1000) +
6899         ((StopTime.tv_usec - StartTime.tv_usec) / 1000);
6900     {
6901         afs_fsize_t targLen;
6902         VN_GET_LEN(targLen, targetptr);
6903         AFSCallStats.TotalFetchedBytes += targLen;
6904         AFSCallStats.FetchSize1++;
6905         if (targLen < SIZE2)
6906             AFSCallStats.FetchSize2++;
6907         else if (targLen < SIZE3)
6908             AFSCallStats.FetchSize3++;
6909         else if (targLen < SIZE4)
6910             AFSCallStats.FetchSize4++;
6911         else
6912             AFSCallStats.FetchSize5++;
6913     }
6914     FS_UNLOCK;
6915     return (0);
6916
6917 }                               /*FetchData_RXStyle */
6918
6919 static int
6920 GetLinkCountAndSize(Volume * vp, FdHandle_t * fdP, int *lc,
6921                     afs_sfsize_t * size)
6922 {
6923 #ifdef AFS_NAMEI_ENV
6924     FdHandle_t *lhp;
6925     lhp = IH_OPEN(V_linkHandle(vp));
6926     if (!lhp)
6927         return EIO;
6928 #ifdef AFS_NT40_ENV
6929     *lc = nt_GetLinkCount(lhp, fdP->fd_ih->ih_ino, 0);
6930 #else
6931     *lc = namei_GetLinkCount(lhp, fdP->fd_ih->ih_ino, 0);
6932 #endif
6933     FDH_CLOSE(lhp);
6934     if (*lc < 0)
6935         return -1;
6936     *size = OS_SIZE(fdP->fd_fd);
6937     return (*size == -1) ? -1 : 0;
6938 #else
6939     struct afs_stat status;
6940
6941     if (afs_fstat(fdP->fd_fd, &status) < 0) {
6942         return -1;
6943     }
6944
6945     *lc = GetLinkCount(vp, &status);
6946     *size = status.st_size;
6947     return 0;
6948 #endif
6949 }
6950
6951 /*
6952  * StoreData_RXStyle
6953  *
6954  * Purpose:
6955  *      Implement a client's data store using Rx.
6956  *
6957  * Arguments:
6958  *      volptr          : Ptr to the given volume's info.
6959  *      targetptr       : Pointer to the vnode involved.
6960  *      Call            : Ptr to the Rx call involved.
6961  *      Pos             : Offset within the file.
6962  *      Len             : Length in bytes to store; this value is bogus!
6963  * if FS_STATS_DETAILED
6964  *      a_bytesToStoreP : Set to the number of bytes to be stored to
6965  *                        the File Server.
6966  *      a_bytesStoredP  : Set to the actual number of bytes stored to
6967  *                        the File Server.
6968  * endif
6969  */
6970 afs_int32
6971 StoreData_RXStyle(Volume * volptr, Vnode * targetptr, struct AFSFid * Fid,
6972                   struct client * client, register struct rx_call * Call,
6973                   afs_fsize_t Pos, afs_fsize_t Length, afs_fsize_t FileLength,
6974                   int sync,
6975 #if FS_STATS_DETAILED
6976                   afs_sfsize_t * a_bytesToStoreP,
6977                   afs_sfsize_t * a_bytesStoredP
6978 #endif                          /* FS_STATS_DETAILED */
6979     )
6980 {
6981     afs_sfsize_t bytesTransfered;       /* number of bytes actually transfered */
6982     struct timeval StartTime, StopTime; /* Used to measure how long the store takes */
6983     int errorCode = 0;          /* Returned error code to caller */
6984 #ifdef AFS_NT40_ENV
6985     register char *tbuffer;     /* data copying buffer */
6986 #else /* AFS_NT40_ENV */
6987     struct iovec tiov[RX_MAXIOVECS];    /* no data copying with iovec */
6988     int tnio;                   /* temp for iovec size */
6989 #endif /* AFS_NT40_ENV */
6990     afs_sfsize_t tlen;          /* temp for xfr length */
6991     Inode tinode;               /* inode for I/O */
6992     afs_int32 optSize;          /* optimal transfer size */
6993     afs_sfsize_t DataLength;    /* size of inode */
6994     afs_sfsize_t TruncatedLength;       /* size after ftruncate */
6995     afs_fsize_t NewLength;      /* size after this store completes */
6996     afs_sfsize_t adjustSize;    /* bytes to call VAdjust... with */
6997     int linkCount;              /* link count on inode */
6998     FdHandle_t *fdP;
6999     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
7000
7001 #if FS_STATS_DETAILED
7002     /*
7003      * Initialize the byte count arguments.
7004      */
7005     (*a_bytesToStoreP) = 0;
7006     (*a_bytesStoredP) = 0;
7007 #endif /* FS_STATS_DETAILED */
7008
7009     /*
7010      * We break the callbacks here so that the following signal will not
7011      * leave a window.
7012      */
7013     BreakCallBack(client->host, Fid, 0);
7014
7015     if (Pos == -1 || VN_GET_INO(targetptr) == 0) {
7016         /* the inode should have been created in Alloc_NewVnode */
7017         logHostAddr.s_addr = rxr_HostOf(rx_ConnectionOf(Call));
7018         ViceLog(0,
7019                 ("StoreData_RXStyle : Inode non-existent Fid = %u.%u.%u, inode = %llu, Pos %llu Host %s:%d\n",
7020                  Fid->Volume, Fid->Vnode, Fid->Unique,
7021                  (afs_uintmax_t) VN_GET_INO(targetptr), (afs_uintmax_t) Pos,
7022                  inet_ntoa(logHostAddr), ntohs(rxr_PortOf(rx_ConnectionOf(Call)))));
7023         return ENOENT;          /* is this proper error code? */
7024     } else {
7025         /*
7026          * See if the file has several links (from other volumes).  If it
7027          * does, then we have to make a copy before changing it to avoid
7028          *changing read-only clones of this dude
7029          */
7030         ViceLog(25,
7031                 ("StoreData_RXStyle : Opening inode %s\n",
7032                  PrintInode(NULL, VN_GET_INO(targetptr))));
7033         fdP = IH_OPEN(targetptr->handle);
7034         if (fdP == NULL)
7035             return ENOENT;
7036         if (GetLinkCountAndSize(volptr, fdP, &linkCount, &DataLength) < 0) {
7037             FDH_CLOSE(fdP);
7038             VTakeOffline(volptr);
7039             return EIO;
7040         }
7041
7042         if (linkCount != 1) {
7043             afs_fsize_t size;
7044             ViceLog(25,
7045                     ("StoreData_RXStyle : inode %s has more than onelink\n",
7046                      PrintInode(NULL, VN_GET_INO(targetptr))));
7047             /* other volumes share this data, better copy it first */
7048
7049             /* Adjust the disk block count by the creation of the new inode.
7050              * We call the special VDiskUsage so we don't adjust the volume's
7051              * quota since we don't want to penalyze the user for afs's internal
7052              * mechanisms (i.e. copy on write overhead.) Also the right size
7053              * of the disk will be recorded...
7054              */
7055             FDH_CLOSE(fdP);
7056             VN_GET_LEN(size, targetptr);
7057             volptr->partition->flags &= ~PART_DONTUPDATE;
7058             VSetPartitionDiskUsage(volptr->partition);
7059             volptr->partition->flags |= PART_DONTUPDATE;
7060             if ((errorCode = VDiskUsage(volptr, nBlocks(size)))) {
7061                 volptr->partition->flags &= ~PART_DONTUPDATE;
7062                 return (errorCode);
7063             }
7064
7065             ViceLog(25, ("StoreData : calling CopyOnWrite on  target dir\n"));
7066             if ((errorCode = CopyOnWrite(targetptr, volptr))) {
7067                 ViceLog(25, ("StoreData : CopyOnWrite failed\n"));
7068                 volptr->partition->flags &= ~PART_DONTUPDATE;
7069                 return (errorCode);
7070             }
7071             volptr->partition->flags &= ~PART_DONTUPDATE;
7072             VSetPartitionDiskUsage(volptr->partition);
7073             fdP = IH_OPEN(targetptr->handle);
7074             if (fdP == NULL) {
7075                 ViceLog(25,
7076                         ("StoreData : Reopen after CopyOnWrite failed\n"));
7077                 return ENOENT;
7078             }
7079         }
7080         tinode = VN_GET_INO(targetptr);
7081     }
7082     assert(VALID_INO(tinode));
7083
7084     /* compute new file length */
7085     NewLength = DataLength;
7086     if (FileLength < NewLength)
7087         /* simulate truncate */
7088         NewLength = FileLength;
7089     TruncatedLength = NewLength;        /* remember length after possible ftruncate */
7090     if (Pos + Length > NewLength)
7091         NewLength = Pos + Length;       /* and write */
7092
7093     /* adjust the disk block count by the difference in the files */
7094     {
7095         afs_fsize_t targSize;
7096         VN_GET_LEN(targSize, targetptr);
7097         adjustSize = nBlocks(NewLength) - nBlocks(targSize);
7098     }
7099     if ((errorCode =
7100          AdjustDiskUsage(volptr, adjustSize,
7101                          adjustSize - SpareComp(volptr)))) {
7102         FDH_CLOSE(fdP);
7103         return (errorCode);
7104     }
7105
7106     /* can signal cache manager to proceed from close now */
7107     /* this bit means that the locks are set and protections are OK */
7108     rx_SetLocalStatus(Call, 1);
7109
7110     TM_GetTimeOfDay(&StartTime, 0);
7111
7112     optSize = sendBufSize;
7113     ViceLog(25,
7114             ("StoreData_RXStyle: Pos %llu, DataLength %llu, FileLength %llu, Length %llu\n",
7115              (afs_uintmax_t) Pos, (afs_uintmax_t) DataLength,
7116              (afs_uintmax_t) FileLength, (afs_uintmax_t) Length));
7117
7118     /* truncate the file iff it needs it (ftruncate is slow even when its a noop) */
7119     if (FileLength < DataLength)
7120         FDH_TRUNC(fdP, FileLength);
7121     if (Pos > 0)
7122         FDH_SEEK(fdP, Pos, 0);
7123     bytesTransfered = 0;
7124 #ifdef AFS_NT40_ENV
7125     tbuffer = AllocSendBuffer();
7126 #endif /* AFS_NT40_ENV */
7127     /* if length == 0, the loop below isn't going to do anything, including
7128      * extend the length of the inode, which it must do, since the file system
7129      * assumes that the inode length == vnode's file length.  So, we extend
7130      * the file length manually if need be.  Note that if file is bigger than
7131      * Pos+(Length==0), we dont' have to do anything, and certainly shouldn't
7132      * do what we're going to do below.
7133      */
7134     if (Length == 0 && Pos > TruncatedLength) {
7135         /* Set the file's length; we've already done an lseek to the right
7136          * spot above.
7137          */
7138         errorCode = FDH_WRITE(fdP, &tlen, 1);
7139         if (errorCode != 1)
7140             goto done;
7141         errorCode = FDH_TRUNC(fdP, Pos);
7142     } else {
7143         /* have some data to copy */
7144 #if FS_STATS_DETAILED
7145         (*a_bytesToStoreP) = Length;
7146 #endif /* FS_STATS_DETAILED */
7147         while (1) {
7148             int rlen;
7149             if (bytesTransfered >= Length) {
7150                 errorCode = 0;
7151                 break;
7152             }
7153             tlen = Length - bytesTransfered;    /* how much more to do */
7154             if (tlen > optSize)
7155                 rlen = optSize; /* bound by buffer size */
7156             else
7157                 rlen = (int)tlen;
7158 #ifdef AFS_NT40_ENV
7159             errorCode = rx_Read(Call, tbuffer, rlen);
7160 #else /* AFS_NT40_ENV */
7161             errorCode = rx_Readv(Call, tiov, &tnio, RX_MAXIOVECS, rlen);
7162 #endif /* AFS_NT40_ENV */
7163 #if FS_STATS_DETAILED
7164             (*a_bytesStoredP) += errorCode;
7165 #endif /* FS_STATS_DETAILED */
7166             if (errorCode <= 0) {
7167                 errorCode = -32;
7168                 break;
7169             }
7170             rlen = errorCode;
7171 #ifdef AFS_NT40_ENV
7172             errorCode = FDH_WRITE(fdP, tbuffer, rlen);
7173 #else /* AFS_NT40_ENV */
7174             errorCode = FDH_WRITEV(fdP, tiov, tnio);
7175 #endif /* AFS_NT40_ENV */
7176             if (errorCode != rlen) {
7177                 errorCode = VDISKFULL;
7178                 break;
7179             }
7180             bytesTransfered += rlen;
7181         }
7182     }
7183   done:
7184 #ifdef AFS_NT40_ENV
7185     FreeSendBuffer((struct afs_buffer *)tbuffer);
7186 #endif /* AFS_NT40_ENV */
7187     if (sync) {
7188         FDH_SYNC(fdP);
7189     }
7190     if (errorCode) {
7191         afs_fsize_t nfSize = (afs_fsize_t) FDH_SIZE(fdP);
7192         /* something went wrong: adjust size and return */
7193         VN_SET_LEN(targetptr, nfSize);  /* set new file size. */
7194         /* changed_newTime is tested in StoreData to detemine if we
7195          * need to update the target vnode.
7196          */
7197         targetptr->changed_newTime = 1;
7198         FDH_CLOSE(fdP);
7199         /* set disk usage to be correct */
7200         VAdjustDiskUsage(&errorCode, volptr,
7201                          (afs_sfsize_t) (nBlocks(nfSize) -
7202                                          nBlocks(NewLength)), 0);
7203         return errorCode;
7204     }
7205     FDH_CLOSE(fdP);
7206
7207     TM_GetTimeOfDay(&StopTime, 0);
7208
7209     VN_SET_LEN(targetptr, NewLength);
7210
7211     /* Update all StoreData related stats */
7212     FS_LOCK;
7213     if (AFSCallStats.TotalStoredBytes > 2000000000)     /* reset if over 2 billion */
7214         AFSCallStats.TotalStoredBytes = AFSCallStats.AccumStoreTime = 0;
7215     AFSCallStats.StoreSize1++;  /* Piggybacked data */
7216     {
7217         afs_fsize_t targLen;
7218         VN_GET_LEN(targLen, targetptr);
7219         if (targLen < SIZE2)
7220             AFSCallStats.StoreSize2++;
7221         else if (targLen < SIZE3)
7222             AFSCallStats.StoreSize3++;
7223         else if (targLen < SIZE4)
7224             AFSCallStats.StoreSize4++;
7225         else
7226             AFSCallStats.StoreSize5++;
7227     }
7228     FS_UNLOCK;
7229     return (errorCode);
7230
7231 }                               /*StoreData_RXStyle */
7232
7233 static int sys2et[512];
7234
7235 void
7236 init_sys_error_to_et(void)
7237 {
7238     memset(&sys2et, 0, sizeof(sys2et));
7239     sys2et[EPERM] = UAEPERM;
7240     sys2et[ENOENT] = UAENOENT;
7241     sys2et[ESRCH] = UAESRCH;
7242     sys2et[EINTR] = UAEINTR;
7243     sys2et[EIO] = UAEIO;
7244     sys2et[ENXIO] = UAENXIO;
7245     sys2et[E2BIG] = UAE2BIG;
7246     sys2et[ENOEXEC] = UAENOEXEC;
7247     sys2et[EBADF] = UAEBADF;
7248     sys2et[ECHILD] = UAECHILD;
7249     sys2et[EAGAIN] = UAEAGAIN;
7250     sys2et[ENOMEM] = UAENOMEM;
7251     sys2et[EACCES] = UAEACCES;
7252     sys2et[EFAULT] = UAEFAULT;
7253     sys2et[ENOTBLK] = UAENOTBLK;
7254     sys2et[EBUSY] = UAEBUSY;
7255     sys2et[EEXIST] = UAEEXIST;
7256     sys2et[EXDEV] = UAEXDEV;
7257     sys2et[ENODEV] = UAENODEV;
7258     sys2et[ENOTDIR] = UAENOTDIR;
7259     sys2et[EISDIR] = UAEISDIR;
7260     sys2et[EINVAL] = UAEINVAL;
7261     sys2et[ENFILE] = UAENFILE;
7262     sys2et[EMFILE] = UAEMFILE;
7263     sys2et[ENOTTY] = UAENOTTY;
7264     sys2et[ETXTBSY] = UAETXTBSY;
7265     sys2et[EFBIG] = UAEFBIG;
7266     sys2et[ENOSPC] = UAENOSPC;
7267     sys2et[ESPIPE] = UAESPIPE;
7268     sys2et[EROFS] = UAEROFS;
7269     sys2et[EMLINK] = UAEMLINK;
7270     sys2et[EPIPE] = UAEPIPE;
7271     sys2et[EDOM] = UAEDOM;
7272     sys2et[ERANGE] = UAERANGE;
7273     sys2et[EDEADLK] = UAEDEADLK;
7274     sys2et[ENAMETOOLONG] = UAENAMETOOLONG;
7275     sys2et[ENOLCK] = UAENOLCK;
7276     sys2et[ENOSYS] = UAENOSYS;
7277 #if (ENOTEMPTY != EEXIST)
7278     sys2et[ENOTEMPTY] = UAENOTEMPTY;
7279 #endif
7280     sys2et[ELOOP] = UAELOOP;
7281 #if (EWOULDBLOCK != EAGAIN)
7282     sys2et[EWOULDBLOCK] = UAEWOULDBLOCK;
7283 #endif
7284     sys2et[ENOMSG] = UAENOMSG;
7285     sys2et[EIDRM] = UAEIDRM;
7286     sys2et[ECHRNG] = UAECHRNG;
7287     sys2et[EL2NSYNC] = UAEL2NSYNC;
7288     sys2et[EL3HLT] = UAEL3HLT;
7289     sys2et[EL3RST] = UAEL3RST;
7290     sys2et[ELNRNG] = UAELNRNG;
7291     sys2et[EUNATCH] = UAEUNATCH;
7292     sys2et[ENOCSI] = UAENOCSI;
7293     sys2et[EL2HLT] = UAEL2HLT;
7294     sys2et[EBADE] = UAEBADE;
7295     sys2et[EBADR] = UAEBADR;
7296     sys2et[EXFULL] = UAEXFULL;
7297     sys2et[ENOANO] = UAENOANO;
7298     sys2et[EBADRQC] = UAEBADRQC;
7299     sys2et[EBADSLT] = UAEBADSLT;
7300     sys2et[EDEADLK] = UAEDEADLK;
7301     sys2et[EBFONT] = UAEBFONT;
7302     sys2et[ENOSTR] = UAENOSTR;
7303     sys2et[ENODATA] = UAENODATA;
7304     sys2et[ETIME] = UAETIME;
7305     sys2et[ENOSR] = UAENOSR;
7306     sys2et[ENONET] = UAENONET;
7307     sys2et[ENOPKG] = UAENOPKG;
7308     sys2et[EREMOTE] = UAEREMOTE;
7309     sys2et[ENOLINK] = UAENOLINK;
7310     sys2et[EADV] = UAEADV;
7311     sys2et[ESRMNT] = UAESRMNT;
7312     sys2et[ECOMM] = UAECOMM;
7313     sys2et[EPROTO] = UAEPROTO;
7314     sys2et[EMULTIHOP] = UAEMULTIHOP;
7315     sys2et[EDOTDOT] = UAEDOTDOT;
7316     sys2et[EBADMSG] = UAEBADMSG;
7317     sys2et[EOVERFLOW] = UAEOVERFLOW;
7318     sys2et[ENOTUNIQ] = UAENOTUNIQ;
7319     sys2et[EBADFD] = UAEBADFD;
7320     sys2et[EREMCHG] = UAEREMCHG;
7321     sys2et[ELIBACC] = UAELIBACC;
7322     sys2et[ELIBBAD] = UAELIBBAD;
7323     sys2et[ELIBSCN] = UAELIBSCN;
7324     sys2et[ELIBMAX] = UAELIBMAX;
7325     sys2et[ELIBEXEC] = UAELIBEXEC;
7326     sys2et[EILSEQ] = UAEILSEQ;
7327     sys2et[ERESTART] = UAERESTART;
7328     sys2et[ESTRPIPE] = UAESTRPIPE;
7329     sys2et[EUSERS] = UAEUSERS;
7330     sys2et[ENOTSOCK] = UAENOTSOCK;
7331     sys2et[EDESTADDRREQ] = UAEDESTADDRREQ;
7332     sys2et[EMSGSIZE] = UAEMSGSIZE;
7333     sys2et[EPROTOTYPE] = UAEPROTOTYPE;
7334     sys2et[ENOPROTOOPT] = UAENOPROTOOPT;
7335     sys2et[EPROTONOSUPPORT] = UAEPROTONOSUPPORT;
7336     sys2et[ESOCKTNOSUPPORT] = UAESOCKTNOSUPPORT;
7337     sys2et[EOPNOTSUPP] = UAEOPNOTSUPP;
7338     sys2et[EPFNOSUPPORT] = UAEPFNOSUPPORT;
7339     sys2et[EAFNOSUPPORT] = UAEAFNOSUPPORT;
7340     sys2et[EADDRINUSE] = UAEADDRINUSE;
7341     sys2et[EADDRNOTAVAIL] = UAEADDRNOTAVAIL;
7342     sys2et[ENETDOWN] = UAENETDOWN;
7343     sys2et[ENETUNREACH] = UAENETUNREACH;
7344     sys2et[ENETRESET] = UAENETRESET;
7345     sys2et[ECONNABORTED] = UAECONNABORTED;
7346     sys2et[ECONNRESET] = UAECONNRESET;
7347     sys2et[ENOBUFS] = UAENOBUFS;
7348     sys2et[EISCONN] = UAEISCONN;
7349     sys2et[ENOTCONN] = UAENOTCONN;
7350     sys2et[ESHUTDOWN] = UAESHUTDOWN;
7351     sys2et[ETOOMANYREFS] = UAETOOMANYREFS;
7352     sys2et[ETIMEDOUT] = UAETIMEDOUT;
7353     sys2et[ECONNREFUSED] = UAECONNREFUSED;
7354     sys2et[EHOSTDOWN] = UAEHOSTDOWN;
7355     sys2et[EHOSTUNREACH] = UAEHOSTUNREACH;
7356     sys2et[EALREADY] = UAEALREADY;
7357     sys2et[EINPROGRESS] = UAEINPROGRESS;
7358     sys2et[ESTALE] = UAESTALE;
7359     sys2et[EUCLEAN] = UAEUCLEAN;
7360     sys2et[ENOTNAM] = UAENOTNAM;
7361     sys2et[ENAVAIL] = UAENAVAIL;
7362     sys2et[EISNAM] = UAEISNAM;
7363     sys2et[EREMOTEIO] = UAEREMOTEIO;
7364     sys2et[EDQUOT] = UAEDQUOT;
7365     sys2et[ENOMEDIUM] = UAENOMEDIUM;
7366     sys2et[EMEDIUMTYPE] = UAEMEDIUMTYPE;
7367 }
7368
7369 /* NOTE:  2006-03-01                                                     
7370  *  SRXAFS_CallBackRxConnAddr should be re-written as follows:           
7371  *  - pass back the connection, client, and host from CallPreamble       
7372  *  - keep a ref on the client, which we don't now                       
7373  *  - keep a hold on the host, which we already do                       
7374  *  - pass the connection, client, and host down into SAFSS_*, and use   
7375  *    them instead of independently discovering them via rx_ConnectionOf 
7376  *    (safe) and rx_GetSpecific (not so safe)                            
7377  *  The idea being that we decide what client and host we're going to use
7378  *  when CallPreamble is called, and stay consistent throughout the call.
7379  *  This change is too invasive for 1.4.1 but should be made in 1.5.x.   
7380  */                                                                      
7381
7382 afs_int32
7383 SRXAFS_CallBackRxConnAddr (struct rx_call * acall, afs_int32 *addr)
7384 {
7385     Error errorCode = 0;
7386     struct rx_connection *tcon;
7387     struct host *tcallhost;
7388 #ifdef __EXPERIMENTAL_CALLBACK_CONN_MOVING
7389     struct host *thost;
7390     struct client *tclient;
7391     static struct rx_securityClass *sc = 0;
7392     int i,j;
7393     struct rx_connection *conn;
7394 #endif
7395     
7396     if (errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &tcallhost))
7397             goto Bad_CallBackRxConnAddr1;
7398     
7399 #ifndef __EXPERIMENTAL_CALLBACK_CONN_MOVING
7400     errorCode = 1;
7401 #else
7402     H_LOCK;
7403     tclient = h_FindClient_r(tcon);
7404     thost = tclient->host;
7405     
7406     /* nothing more can be done */
7407     if ( !thost->interface ) 
7408         goto Bad_CallBackRxConnAddr;
7409     
7410     assert(thost->interface->numberOfInterfaces > 0 );
7411     
7412     /* the only address is the primary interface */
7413     /* can't change when there's only 1 address, anyway */
7414     if ( thost->interface->numberOfInterfaces == 1 ) 
7415         goto Bad_CallBackRxConnAddr;
7416     
7417     /* initialise a security object only once */
7418     if ( !sc )
7419         sc = (struct rx_securityClass *) rxnull_NewClientSecurityObject();
7420     
7421     for ( i=0; i < thost->interface->numberOfInterfaces; i++)
7422     {
7423             if ( *addr == thost->interface->addr[i] ) {
7424                     break;
7425             }
7426     }
7427     
7428     if ( *addr != thost->interface->addr[i] ) 
7429         goto Bad_CallBackRxConnAddr;
7430
7431     conn = rx_NewConnection (thost->interface->addr[i],
7432                              thost->port, 1, sc, 0);
7433     rx_SetConnDeadTime(conn, 2); 
7434     rx_SetConnHardDeadTime(conn, AFS_HARDDEADTIME); 
7435     H_UNLOCK;
7436     errorCode = RXAFSCB_Probe(conn);
7437     H_LOCK;
7438     if (!errorCode) {
7439         if ( thost->callback_rxcon )
7440             rx_DestroyConnection(thost->callback_rxcon);
7441         thost->callback_rxcon = conn;
7442         thost->host           = addr;
7443         rx_SetConnDeadTime(thost->callback_rxcon, 50);
7444         rx_SetConnHardDeadTime(thost->callback_rxcon, AFS_HARDDEADTIME);
7445         h_ReleaseClient_r(tclient);
7446         /* The hold on thost will be released by CallPostamble */
7447         H_UNLOCK;
7448         errorCode = CallPostamble(tcon, errorCode, tcallhost);
7449         return errorCode;
7450     } else {
7451         rx_DestroyConnection(conn);
7452     }       
7453   Bad_CallBackRxConnAddr:
7454     h_ReleaseClient_r(tclient);
7455     /* The hold on thost will be released by CallPostamble */
7456     H_UNLOCK;
7457 #endif
7458
7459     errorCode = CallPostamble(tcon, errorCode, tcallhost);
7460  Bad_CallBackRxConnAddr1:
7461     return errorCode;          /* failure */
7462 }
7463
7464 afs_int32
7465 sys_error_to_et(afs_int32 in)
7466 {
7467     if (in == 0)
7468         return 0;
7469     if (in < 0 || in > 511)
7470         return in;
7471     if (in >= VICE_SPECIAL_ERRORS && in <= VIO || in == VRESTRICTED)
7472         return in;
7473     if (sys2et[in] != 0)
7474         return sys2et[in];
7475     return in;
7476 }