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