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