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