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