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