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