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