source: rtems/cpukit/libfs/src/nfsclient/src/nfs.c @ e16111b2

5
Last change on this file since e16111b2 was e16111b2, checked in by Sebastian Huber <sebastian.huber@…>, on 02/07/18 at 07:57:18

NFS: Fix use of self-contained objects

Update #2843.

  • Property mode set to 100644
File size: 71.5 KB
Line 
1/**
2 * @file
3 *
4 * @brief NFS Client Implementation for RTEMS
5 * @ingroup libfs
6 *
7 * Hooks Into the RTEMS NFS Filesystem
8 */
9
10/*
11 * Author: Till Straumann <strauman@slac.stanford.edu>, 2002
12 *
13 * Hacked on by others.
14 *
15 * Modifications to support reference counting in the file system are
16 * Copyright (c) 2012 embedded brains GmbH.
17 *
18 * Authorship
19 * ----------
20 * This software (NFS-2 client implementation for RTEMS) was created by
21 *     Till Straumann <strauman@slac.stanford.edu>, 2002-2007,
22 *         Stanford Linear Accelerator Center, Stanford University.
23 *
24 * Acknowledgement of sponsorship
25 * ------------------------------
26 * The NFS-2 client implementation for RTEMS was produced by
27 *     the Stanford Linear Accelerator Center, Stanford University,
28 *         under Contract DE-AC03-76SFO0515 with the Department of Energy.
29 *
30 * Government disclaimer of liability
31 * ----------------------------------
32 * Neither the United States nor the United States Department of Energy,
33 * nor any of their employees, makes any warranty, express or implied, or
34 * assumes any legal liability or responsibility for the accuracy,
35 * completeness, or usefulness of any data, apparatus, product, or process
36 * disclosed, or represents that its use would not infringe privately owned
37 * rights.
38 *
39 * Stanford disclaimer of liability
40 * --------------------------------
41 * Stanford University makes no representations or warranties, express or
42 * implied, nor assumes any liability for the use of this software.
43 *
44 * Stanford disclaimer of copyright
45 * --------------------------------
46 * Stanford University, owner of the copyright, hereby disclaims its
47 * copyright and all other rights in this software.  Hence, anyone may
48 * freely use it for any purpose without restriction.
49 *
50 * Maintenance of notices
51 * ----------------------
52 * In the interest of clarity regarding the origin and status of this
53 * SLAC software, this and all the preceding Stanford University notices
54 * are to remain affixed to any copy or derivative of this software made
55 * or distributed by the recipient and are to be affixed to any copy of
56 * software made or distributed by the recipient that contains a copy or
57 * derivative of this software.
58 *
59 * ------------------ SLAC Software Notices, Set 4 OTT.002a, 2004 FEB 03
60 */
61
62#ifdef  HAVE_CONFIG_H
63#include <config.h>
64#endif
65
66#include <rtems.h>
67#include <rtems/libio.h>
68#include <rtems/libio_.h>
69#include <rtems/seterr.h>
70#include <rtems/thread.h>
71#include <string.h>
72#include <stdio.h>
73#include <stdint.h>
74#include <stdlib.h>
75#include <assert.h>
76#include <sys/stat.h>
77#include <dirent.h>
78#include <netdb.h>
79#include <ctype.h>
80#include <netinet/in.h>
81#include <arpa/inet.h>
82
83#include <nfs_prot.h>
84#include <mount_prot.h>
85
86#include "rpcio.h"
87#include "librtemsNfs.h"
88
89/* Configurable parameters */
90
91/* Estimated average length of a filename (including terminating 0).
92 * This was calculated by doing
93 *
94 *      find <some root> -print -exec basename '{}' \; > feil
95 *      wc feil
96 *
97 * AVG_NAMLEN = (num_chars + num_lines)/num_lines
98 */
99#define CONFIG_AVG_NAMLEN                               10
100
101#define CONFIG_NFS_SMALL_XACT_SIZE              800                     /* size of RPC arguments for non-write ops */
102/* lifetime of NFS attributes in a NfsNode;
103 * the time is in seconds and the lifetime is
104 * infinite if the symbol is #undef
105 */
106#define CONFIG_ATTR_LIFETIME                    10/*secs*/
107
108/*
109 * The 'st_blksize' (stat(2)) value this nfs
110 * client should report. If set to zero then the server's fattr data
111 * is passed throught which is not necessary optimal.
112 * Newlib's stdio uses 'st_blksize' (if built with HAVE_BLKSIZE defined)
113 * to size the default buffer.
114 * Due to the overhead of NFS it is probably better to use the maximum
115 * size of an NFS read request (8k) rather than the optimal block
116 * size on the server.
117 * This value can be overridden at run-time by setting the global
118 * variable 'nfsStBlksize'.
119 * Thanks to Steven Johnson <sjohnson@sakuraindustries.com> for helping
120 * working on this issue.
121 */
122#define DEFAULT_NFS_ST_BLKSIZE                  NFS_MAXDATA
123
124/* dont change this without changing the maximal write size */
125#define CONFIG_NFS_BIG_XACT_SIZE                UDPMSGSIZE      /* dont change this */
126
127/* The real values for these are specified further down */
128#define NFSCALL_TIMEOUT                                 (&_nfscalltimeout)
129#define MNTCALL_TIMEOUT                                 (&_nfscalltimeout)
130static struct timeval _nfscalltimeout = { 10, 0 };      /* {secs, us } */
131
132/* More or less fixed constants; in particular, NFS3 is not supported */
133#define DELIM                                                   '/'
134#define HOSTDELIM                                               ':'
135#define UPDIR                                                   ".."
136#define UIDSEP                                                  '@'
137#define NFS_VERSION_2                                   NFS_VERSION
138
139/* we use a dynamically assigned major number */
140#define NFS_MAJOR                                               (nfsGlob.nfs_major)
141
142
143/* NOTE: RTEMS (ss-20020301) uses a 'short st_ino' type :-( but the
144 * NFS fileid is 32 bit. [Later versions of RTEMS have fixed this;
145 * nfsInit() issues a warning if you run a version with 'short st_ino'.]
146 *
147 * As a workarount, we merge the upper 16bits of the fileid into the
148 * minor device no. Hence, it is still possible to uniquely identify
149 * a file by looking at its device number (major = nfs, minor = part
150 * of the fileid + our 'nfs-id' identifier).
151 *
152 * This has an impact on performance, as e.g. getcwd() stats() all
153 * directory entries when it believes it has crossed a mount point
154 * (a.st_dev != b.st_dev).
155 *
156 * OTOH, it also might cause node comparison failure! E.g. 'getcwd()'
157 * assumes that two nodes residing in the same directory must be located
158 * on the same device and hence compares 'st_ino' only.
159 * If two files in the same directory have the same inode number
160 * modulo 2^16, they will be considered equal (although their device
161 * number doesn't match - getcwd doesn't look at it).
162 *
163 * Other software might or might not be affected.
164 *
165 * The only clean solution to this problem is bumping up the size of
166 * 'ino_t' at least to 'long'.
167 * Note that this requires _all_ software (libraries etc.) to be
168 * recompiled.
169 */
170
171#define NFS_MAKE_DEV_T_INO_HACK(node) \
172                rtems_filesystem_make_dev_t( NFS_MAJOR, \
173                        (((rtems_device_minor_number)((node)->nfs->id))<<16) | (((rtems_device_minor_number)SERP_ATTR((node)).fileid) >> 16) )
174
175/* use our 'nfs id' and the server's fsid for the minor device number
176 * this should be fairly unique
177 */
178#define NFS_MAKE_DEV_T(node) \
179                rtems_filesystem_make_dev_t( NFS_MAJOR, \
180                        (((rtems_device_minor_number)((node)->nfs->id))<<16) | (SERP_ATTR((node)).fsid & (((rtems_device_minor_number)1<<16)-1)) )
181
182#define  DIRENT_HEADER_SIZE ( sizeof(struct dirent) - \
183                        sizeof( ((struct dirent *)0)->d_name ) )
184
185
186/* debugging flags */
187#define DEBUG_COUNT_NODES       (1<<0)
188#define DEBUG_TRACK_NODES       (1<<1)
189#define DEBUG_EVALPATH          (1<<2)
190#define DEBUG_READDIR           (1<<3)
191#define DEBUG_SYSCALLS          (1<<4)
192
193/* #define DEBUG        ( DEBUG_SYSCALLS | DEBUG_COUNT_NODES ) */
194
195#ifdef DEBUG
196#define STATIC
197#else
198#define STATIC static
199#endif
200
201#define LOCK(s)         rtems_recursive_mutex_lock(&(s))
202
203#define UNLOCK(s)       rtems_recursive_mutex_unlock(&(s))
204
205RTEMS_INTERRUPT_LOCK_DEFINE(static, nfs_global_lock, "NFS")
206
207#define NFS_GLOBAL_ACQUIRE(lock_context) \
208    rtems_interrupt_lock_acquire(&nfs_global_lock, lock_context)
209
210#define NFS_GLOBAL_RELEASE(lock_context) \
211    rtems_interrupt_lock_release(&nfs_global_lock, lock_context)
212
213static inline char *
214nfs_dupname(const char *name, size_t namelen)
215{
216        char *dupname = malloc(namelen + 1);
217
218        if (dupname != NULL) {
219                memcpy(dupname, name, namelen);
220                dupname [namelen] = '\0';
221        } else {
222                errno = ENOMEM;
223        }
224
225        return dupname;
226}
227
228/*****************************************
229        Types with Associated XDR Routines
230 *****************************************/
231
232/* a string buffer with a maximal length.
233 * If the buffer pointer is NULL, it is updated
234 * with an appropriately allocated area.
235 */
236typedef struct strbuf {
237        char    *buf;
238        u_int   max;
239} strbuf;
240
241/* Read 'readlink' results into a 'strbuf'.
242 * This is convenient as it avoids
243 * one extra step of copying / length
244 * checking.
245 */
246typedef struct readlinkres_strbuf {
247        nfsstat status;
248        strbuf  strbuf;
249} readlinkres_strbuf;
250
251static bool_t
252xdr_readlinkres_strbuf(XDR *xdrs, readlinkres_strbuf *objp)
253{
254        if ( !xdr_nfsstat(xdrs, &objp->status) )
255                return FALSE;
256
257        if ( NFS_OK == objp->status ) {
258                if ( !xdr_string(xdrs, &objp->strbuf.buf, objp->strbuf.max) )
259                        return FALSE;
260        }
261        return TRUE;
262}
263
264
265/* DirInfoRec is used instead of dirresargs
266 * to convert recursion into iteration. The
267 * 'rpcgen'erated xdr_dirresargs ends up
268 * doing nested calls when unpacking the
269 * 'next' pointers.
270 */
271
272typedef struct DirInfoRec_ {
273        readdirargs     readdirargs;
274        /* clone of the 'readdirres' fields;
275         * the cookie is put into the readdirargs above
276         */
277        nfsstat         status;
278        char            *buf, *ptr;
279        int                     len;
280        bool_t          eofreached;
281} DirInfoRec, *DirInfo;
282
283/* this deals with one entry / record */
284static bool_t
285xdr_dir_info_entry(XDR *xdrs, DirInfo di)
286{
287union   {
288        char                    nambuf[NFS_MAXNAMLEN+1];
289        nfscookie               cookie;
290}                               dummy;
291struct dirent   *pde = (struct dirent *)di->ptr;
292u_int                   fileid;
293char                    *name;
294register int    nlen = 0,len,naligned = 0;
295nfscookie               *pcookie;
296
297        len = di->len;
298
299        if ( !xdr_u_int(xdrs, &fileid) )
300                return FALSE;
301
302        /* we must pass the address of a char* */
303        name = (len > NFS_MAXNAMLEN) ? pde->d_name : dummy.nambuf;
304
305        if ( !xdr_filename(xdrs, &name) ) {
306                return FALSE;
307        }
308
309        if (len >= 0) {
310                nlen      = strlen(name);
311                naligned  = nlen + 1 /* string delimiter */ + 3 /* alignment */;
312                naligned &= ~3;
313                len      -= naligned;
314        }
315
316        /* if the cookie goes into the DirInfo, we hope this doesn't fail
317         * - the caller ends up with an invalid readdirargs cookie otherwise...
318         */
319        pcookie = (len >= 0) ? &di->readdirargs.cookie : &dummy.cookie;
320        if ( !xdr_nfscookie(xdrs, pcookie) ) {
321                return FALSE;
322        }
323
324        di->len = len;
325        /* adjust the buffer pointer */
326        if (len >= 0) {
327                pde->d_ino    = fileid;
328                pde->d_namlen = nlen;
329                pde->d_off        = di->ptr - di->buf;
330                if (name == dummy.nambuf) {
331                        memcpy(pde->d_name, dummy.nambuf, nlen + 1);
332                }
333                pde->d_reclen = DIRENT_HEADER_SIZE + naligned;
334                di->ptr      += pde->d_reclen;
335        }
336
337        return TRUE;
338}
339
340/* this routine loops over all entries */
341static bool_t
342xdr_dir_info(XDR *xdrs, DirInfo di)
343{
344DirInfo dip;
345
346        if ( !xdr_nfsstat(xdrs, &di->status) )
347                return FALSE;
348
349        if ( NFS_OK != di->status )
350                return TRUE;
351
352        dip = di;
353
354        while (dip) {
355                /* reserve space for the dirent 'header' - we assume it's word aligned! */
356#ifdef DEBUG
357                assert( DIRENT_HEADER_SIZE % 4 == 0 );
358#endif
359                dip->len -= DIRENT_HEADER_SIZE;
360
361                /* we pass a 0 size - size is unused since
362                 * we always pass a non-NULL pointer
363                 */
364                if ( !xdr_pointer(xdrs, (void*)&dip, 0 /* size */, (xdrproc_t)xdr_dir_info_entry) )
365                        return FALSE;
366        }
367
368        if ( ! xdr_bool(xdrs, &di->eofreached) )
369                return FALSE;
370
371        /* if everything fits into the XDR buffer but not the user's buffer,
372         * they must resume reading from where xdr_dir_info_entry() started
373         * skipping and 'eofreached' needs to be adjusted
374         */
375        if ( di->len < 0 && di->eofreached )
376                di->eofreached = FALSE;
377
378        return TRUE;
379}
380
381
382/* a type better suited for node operations
383 * than diropres.
384 * fattr and fhs are swapped so parts of this
385 * structure may be used as a diroparg which
386 * is practical when looking up paths.
387 */
388
389/* Macro for accessing serporid fields
390 */
391#define SERP_ARGS(node) ((node)->serporid.serporid_u.serporid.arg_u)
392#define SERP_ATTR(node) ((node)->serporid.serporid_u.serporid.attributes)
393#define SERP_FILE(node) ((node)->serporid.serporid_u.serporid.file)
394
395
396typedef struct serporidok {
397        fattr                                   attributes;
398        nfs_fh                                  file;
399        union   {
400                struct {
401                        filename        name;
402                }                                       diroparg;
403                struct {
404                        sattr           attributes;
405                }                                       sattrarg;
406                struct {
407                        uint32_t        offset;
408                        uint32_t        count;
409                        uint32_t        totalcount;
410                }                                       readarg;
411                struct {
412                        uint32_t        beginoffset;
413                        uint32_t        offset;
414                        uint32_t        totalcount;
415                        struct {
416                                uint32_t data_len;
417                                char* data_val;
418                        }                       data;
419                }                                       writearg;
420                struct {
421                        filename        name;
422                        sattr           attributes;
423                }                                       createarg;
424                struct {
425                        filename        name;
426                        diropargs       to;
427                }                                       renamearg;
428                struct {
429                        diropargs       to;
430                }                                       linkarg;
431                struct {
432                        filename        name;
433                        nfspath         to;
434                        sattr           attributes;
435                }                                       symlinkarg;
436                struct {
437                        nfscookie       cookie;
438                        uint32_t        count;
439                }                                       readdirarg;
440        }                                                       arg_u;
441} serporidok;
442
443typedef struct serporid {
444        nfsstat                 status;
445        union   {
446                serporidok      serporid;
447        }                               serporid_u;
448} serporid;
449
450/* an XDR routine to encode/decode the inverted diropres
451 * into an nfsnodestat;
452 *
453 * NOTE: this routine only acts on
454 *   - 'serporid.status'
455 *   - 'serporid.file'
456 *   - 'serporid.attributes'
457 * and leaves the 'arg_u' alone.
458 *
459 * The idea is that a 'diropres' is read into 'serporid'
460 * which can then be used as an argument to subsequent
461 * NFS-RPCs (after filling in the node's arg_u).
462 */
463static bool_t
464xdr_serporidok(XDR *xdrs, serporidok *objp)
465{
466     if (!xdr_nfs_fh (xdrs, &objp->file))
467         return FALSE;
468     if (!xdr_fattr (xdrs, &objp->attributes))
469         return FALSE;
470    return TRUE;
471}
472
473static bool_t
474xdr_serporid(XDR *xdrs, serporid *objp)
475{
476     if (!xdr_nfsstat (xdrs, &objp->status))
477         return FALSE;
478    switch (objp->status) {
479    case NFS_OK:
480         if (!xdr_serporidok(xdrs, &objp->serporid_u.serporid))
481             return FALSE;
482        break;
483    default:
484        break;
485    }
486    return TRUE;
487}
488
489/*****************************************
490        Data Structures and Types
491 *****************************************/
492
493/* 'time()' hack with less overhead; */
494
495/* assume reading a long word is atomic */
496#define READ_LONG_IS_ATOMIC
497
498typedef uint32_t        TimeStamp;
499
500static inline TimeStamp
501nowSeconds(void)
502{
503  rtems_interval rval;
504  rtems_clock_get_seconds_since_epoch( &rval );
505  return rval;
506}
507
508
509/* Per mounted FS structure */
510typedef struct NfsRec_ {
511                /* the NFS server we're talking to.
512                 */
513        RpcUdpServer                                             server;
514                /* statistics; how many NfsNodes are
515                 * currently alive.
516                 */
517        volatile int                                             nodesInUse;
518#if DEBUG & DEBUG_COUNT_NODES
519                /* statistics; how many 'NfsNode.str'
520                 * strings are currently allocated.
521                 */
522        volatile int                                             stringsInUse;
523#endif
524                /* A small number who uniquely
525                 * identifies a mounted NFS within
526                 * this driver (i.e. this NfsRec).
527                 * Each time a NFS is mounted, the
528                 * global ID counter is incremented
529                 * and its value is assigned to the
530                 * newly created NfsRec.
531                 */
532        u_short                                                          id;
533                /* Our RTEMS filesystem mt_entry
534                 */
535        rtems_filesystem_mount_table_entry_t *mt_entry;
536                /* Next NfsRec on a linked list who
537                 * is anchored at nfsGlob
538                 */
539        struct NfsRec_                                           *next;
540                /* Who we pretend we are
541                 */
542        u_long                                                           uid,gid;
543} NfsRec, *Nfs;
544
545typedef struct NfsNodeRec_ {
546                /* This holds this node's attributes
547                 * (stats) and its nfs filehandle.
548                 * It also contains room for nfs rpc
549                 * arguments.
550                 */
551        serporid        serporid;
552                /* The arguments we used when doing
553                 * the 'lookup' call for this node.
554                 * We need this information (especially
555                 * the directory FH) for performing
556                 * certain operations on this
557                 * node (in particular: for unlinking
558                 * it from a parent directory)
559                 */
560        diropargs               args;
561                /* FS this node belongs to
562                 */
563        Nfs                             nfs;
564                /* A buffer for the string the
565                 * args.name points to.
566                 * We need this because args.name might
567                 * temporarily point to strings on the
568                 * stack. Duplicates are allocated from
569                 * the heap and attached to 'str' so
570                 * they can be released as appropriate.
571                 */
572        char               *str;
573                /* A timestamp for the stats
574                 */
575        TimeStamp               age;
576} NfsNodeRec, *NfsNode;
577
578/*****************************************
579        Forward Declarations
580 *****************************************/
581
582static ssize_t nfs_readlink_with_node(
583        NfsNode node,
584        char *buf,
585        size_t len
586);
587
588static int updateAttr(NfsNode node, int force);
589
590/* Mask bits when setting attributes.
591 * Only the 'arg' fields with their
592 * corresponding bit set in the mask
593 * will be used. The others are left
594 * unchanged.
595 * The 'TOUCH' bits instruct nfs_sattr()
596 * to update the respective time
597 * fields to the current time
598 */
599#define SATTR_MODE              (1<<0)
600#define SATTR_UID               (1<<1)
601#define SATTR_GID               (1<<2)
602#define SATTR_SIZE              (1<<3)
603#define SATTR_ATIME             (1<<4)
604#define SATTR_TOUCHA    (1<<5)
605#define SATTR_MTIME             (1<<6)
606#define SATTR_TOUCHM    (1<<7)
607#define SATTR_TOUCH             (SATTR_TOUCHM | SATTR_TOUCHA)
608
609static int
610nfs_sattr(NfsNode node, sattr *arg, u_long mask);
611
612extern const struct _rtems_filesystem_operations_table nfs_fs_ops;
613static const struct _rtems_filesystem_file_handlers_r nfs_file_file_handlers;
614static const struct _rtems_filesystem_file_handlers_r nfs_dir_file_handlers;
615static const struct _rtems_filesystem_file_handlers_r nfs_link_file_handlers;
616static             rtems_driver_address_table            drvNfs;
617
618int
619nfsMountsShow(FILE*);
620
621rtems_status_code
622rtems_filesystem_resolve_location(char *buf, int len, rtems_filesystem_location_info_t *loc);
623
624/*****************************************
625        Global Variables
626 *****************************************/
627
628/* These are (except for MAXNAMLEN/MAXPATHLEN) copied from IMFS */
629
630static const rtems_filesystem_limits_and_options_t
631nfs_limits_and_options = {
632   5,                           /* link_max */
633   6,                           /* max_canon */
634   7,                           /* max_input */
635   NFS_MAXNAMLEN,       /* name_max */
636   NFS_MAXPATHLEN,      /* path_max */
637   2,                           /* pipe_buf */
638   1,                           /* posix_async_io */
639   2,                           /* posix_chown_restrictions */
640   3,                           /* posix_no_trunc */
641   4,                           /* posix_prio_io */
642   5,                           /* posix_sync_io */
643   6                            /* posix_vdisable */
644};
645
646/* size of an encoded 'entry' object */
647static int dirres_entry_size;
648
649/* Global stuff and statistics */
650static struct nfsstats {
651                /* A lock for protecting the
652                 * linked ist of mounted NFS
653                 * and the num_mounted_fs field
654                 */
655        rtems_recursive_mutex                   llock;
656                /* A lock for protecting misc
657                 * stuff  within the driver.
658                 * The lock must only be held
659                 * for short periods of time.
660                 */
661        rtems_recursive_mutex                   lock;
662                /* Our major number as assigned
663                 * by RTEMS
664                 */
665        rtems_device_major_number       nfs_major;
666                /* The number of currently
667                 * mounted NFS
668                 */
669        int                                                     num_mounted_fs;
670                /* A list of the currently
671                 * mounted NFS
672                 */
673        struct NfsRec_                          *mounted_fs;
674                /* A counter for allocating
675                 * unique IDs to each mounted
676                 * NFS.
677                 * Assume we are not going to
678                 * do more than 16k mounts
679                 * during the system lifetime
680                 */
681        u_short                                         fs_ids;
682
683        /* Two pools of RPC transactions;
684         * One with small send buffers
685         * the other with a big one.
686         * The actual size of the small
687         * buffer is configurable (see top).
688         *
689         * Note: The RX buffers are always
690         * big
691         */
692        RpcUdpXactPool smallPool;
693        RpcUdpXactPool bigPool;
694} nfsGlob = {RTEMS_RECURSIVE_MUTEX_INITIALIZER("NFS List"), RTEMS_RECURSIVE_MUTEX_INITIALIZER("NFS Misc"),  0xffffffff, 0, 0, 0, NULL, NULL};
695
696/*
697 * Global variable to tune the 'st_blksize' (stat(2)) value this nfs
698 * client should report.
699 * size on the server.
700 */
701#ifndef DEFAULT_NFS_ST_BLKSIZE
702#define DEFAULT_NFS_ST_BLKSIZE  NFS_MAXDATA
703#endif
704int nfsStBlksize = DEFAULT_NFS_ST_BLKSIZE;
705
706
707/*****************************************
708        Implementation
709 *****************************************/
710
711static int nfsEvaluateStatus(nfsstat nfsStatus)
712{
713        static const uint8_t nfsStatusToErrno [71] = {
714                [NFS_OK] = 0,
715                [NFSERR_PERM] = EPERM,
716                [NFSERR_NOENT] = ENOENT,
717                [3] = EIO,
718                [4] = EIO,
719                [NFSERR_IO] = EIO,
720                [NFSERR_NXIO] = ENXIO,
721                [7] = EIO,
722                [8] = EIO,
723                [9] = EIO,
724                [10] = EIO,
725                [11] = EIO,
726                [12] = EIO,
727                [NFSERR_ACCES] = EACCES,
728                [14] = EIO,
729                [15] = EIO,
730                [16] = EIO,
731                [NFSERR_EXIST] = EEXIST,
732                [18] = EIO,
733                [NFSERR_NODEV] = ENODEV,
734                [NFSERR_NOTDIR] = ENOTDIR,
735                [NFSERR_ISDIR] = EISDIR,
736                [22] = EIO,
737                [24] = EIO,
738                [25] = EIO,
739                [26] = EIO,
740                [27] = EIO,
741                [NFSERR_FBIG] = EFBIG,
742                [NFSERR_NOSPC] = ENOSPC,
743                [29] = EIO,
744                [NFSERR_ROFS] = EROFS,
745                [31] = EIO,
746                [32] = EIO,
747                [34] = EIO,
748                [35] = EIO,
749                [36] = EIO,
750                [37] = EIO,
751                [38] = EIO,
752                [39] = EIO,
753                [40] = EIO,
754                [41] = EIO,
755                [42] = EIO,
756                [44] = EIO,
757                [45] = EIO,
758                [46] = EIO,
759                [47] = EIO,
760                [48] = EIO,
761                [49] = EIO,
762                [50] = EIO,
763                [51] = EIO,
764                [52] = EIO,
765                [54] = EIO,
766                [55] = EIO,
767                [56] = EIO,
768                [57] = EIO,
769                [58] = EIO,
770                [59] = EIO,
771                [60] = EIO,
772                [61] = EIO,
773                [62] = EIO,
774                [NFSERR_NAMETOOLONG] = ENAMETOOLONG,
775                [64] = EIO,
776                [65] = EIO,
777                [NFSERR_NOTEMPTY] = ENOTEMPTY,
778                [67] = EIO,
779                [68] = EIO,
780                [NFSERR_DQUOT] = EDQUOT,
781                [NFSERR_STALE] = ESTALE
782        };
783
784        size_t idx = (size_t) nfsStatus;
785        int eno = EIO;
786        int rv = 0;
787
788        if (idx < sizeof(nfsStatusToErrno) / sizeof(nfsStatusToErrno [0])) {
789                eno = nfsStatusToErrno [idx];
790        }
791
792        if (eno != 0) {
793                errno = eno;
794                rv = -1;
795        }
796
797        return rv;
798}
799
800/* Create a Nfs object. This is
801 * per-mounted NFS information.
802 *
803 * ARGS:        The Nfs server handle.
804 *
805 * RETURNS:     Nfs on success,
806 *                      NULL on failure with
807 *                      errno set
808 *
809 * NOTE:        The submitted server
810 *                      object is 'owned' by
811 *                      this Nfs and will be
812 *                      destroyed by nfsDestroy()
813 */
814static Nfs
815nfsCreate(RpcUdpServer server)
816{
817Nfs rval = calloc(1,sizeof(*rval));
818
819        if (rval) {
820                rval->server     = server;
821                LOCK(nfsGlob.llock);
822                        rval->next                 = nfsGlob.mounted_fs;
823                        nfsGlob.mounted_fs = rval;
824                UNLOCK(nfsGlob.llock);
825        } else {
826                errno = ENOMEM;
827        }
828                return rval;
829}
830
831/* Destroy an Nfs object and
832 * its associated server
833 */
834static void
835nfsDestroy(Nfs nfs)
836{
837register Nfs prev;
838        if (!nfs)
839                return;
840
841        LOCK(nfsGlob.llock);
842                if (nfs == nfsGlob.mounted_fs)
843                        nfsGlob.mounted_fs = nfs->next;
844                else {
845                        for (prev = nfsGlob.mounted_fs;
846                                 prev && prev->next != nfs;
847                                 prev = prev->next)
848                                        /* nothing else to do */;
849                        assert( prev );
850                        prev->next = nfs->next;
851                }
852        UNLOCK(nfsGlob.llock);
853
854        nfs->next = 0; /* paranoia */
855        rpcUdpServerDestroy(nfs->server);
856        free(nfs);
857}
858
859/*
860 * Create a Node. The node will
861 * be associated with a particular
862 * mounted NFS identified by 'nfs'
863 * Optionally, a NFS file handle
864 * may be copied into this node.
865 *
866 * ARGS:        nfs of the NFS this node
867 *                      belongs to.
868 *                      NFS file handle identifying
869 *                      this node.
870 * RETURNS:     node on success,
871 *                      NULL on failure with errno
872 *                      set.
873 *
874 * NOTE:        The caller of this routine
875 *                      is responsible for copying
876 *                      a NFS file handle if she
877 *                      choses to pass a NULL fh.
878 *
879 *                      The driver code assumes the
880 *                      a node always has a valid
881 *                      NFS filehandle and file
882 *                      attributes (unless the latter
883 *                      are aged).
884 */
885static NfsNode
886nfsNodeCreate(Nfs nfs, fhandle *fh)
887{
888NfsNode rval = malloc(sizeof(*rval));
889rtems_interrupt_lock_context lock_context;
890
891#if DEBUG & DEBUG_TRACK_NODES
892        fprintf(stderr,"NFS: creating a node\n");
893#endif
894
895        if (rval) {
896                if (fh)
897                        memcpy( &SERP_FILE(rval), fh, sizeof(*fh) );
898                NFS_GLOBAL_ACQUIRE(&lock_context);
899                        nfs->nodesInUse++;
900                NFS_GLOBAL_RELEASE(&lock_context);
901                rval->nfs       = nfs;
902                rval->str               = 0;
903        } else {
904                errno = ENOMEM;
905        }
906
907        return rval;
908}
909
910/* destroy a node */
911static void
912nfsNodeDestroy(NfsNode node)
913{
914rtems_interrupt_lock_context lock_context;
915
916#if DEBUG & DEBUG_TRACK_NODES
917        fprintf(stderr,"NFS: destroying a node\n");
918#endif
919#if 0
920        if (!node)
921                return;
922        /* this probably does nothing... */
923        xdr_free(xdr_serporid, &node->serporid);
924#endif
925
926        NFS_GLOBAL_ACQUIRE(&lock_context);
927                node->nfs->nodesInUse--;
928#if DEBUG & DEBUG_COUNT_NODES
929                if (node->str)
930                        node->nfs->stringsInUse--;
931#endif
932        NFS_GLOBAL_RELEASE(&lock_context);
933
934        if (node->str)
935                free(node->str);
936
937        free(node);
938}
939
940/* Clone a given node (AKA copy constructor),
941 * i.e. create an exact copy.
942 *
943 * ARGS:        node to clone
944 * RETURNS:     new node on success
945 *                      NULL on failure with errno set.
946 *
947 * NOTE:        a string attached to 'str'
948 *                      is cloned as well. Outdated
949 *                      attributes (of the new copy
950 *                      only) will be refreshed
951 *                      (if unsuccessful, this could
952 *                      be a reason for failure to
953 *                      clone a node).
954 */
955static NfsNode
956nfsNodeClone(NfsNode node)
957{
958NfsNode rval = nfsNodeCreate(node->nfs, 0);
959
960        if (rval) {
961                *rval = *node;
962
963                /* must clone the string also */
964                if (node->str) {
965                        rval->args.name = rval->str = strdup(node->str);
966                        if (!rval->str) {
967                                errno = ENOMEM;
968                                nfsNodeDestroy(rval);
969                                return 0;
970                        }
971#if DEBUG & DEBUG_COUNT_NODES
972                        { rtems_interrupt_lock_context lock_context;
973                        NFS_GLOBAL_ACQUIRE(&lock_context);
974                                node->nfs->stringsInUse++;
975                        NFS_GLOBAL_RELEASE(&lock_context);
976                        }
977#endif
978                }
979
980                /* possibly update the stats */
981                if (updateAttr(rval, 0 /* only if necessary */)) {
982                        nfsNodeDestroy(rval);
983                        return 0;
984                }
985        }
986        return rval;
987}
988
989/* Initialize the driver.
990 *
991 * ARGS:        depth of the small and big
992 *                      transaction pools, i.e. how
993 *                      many transactions (buffers)
994 *                      should always be kept around.
995 *
996 *                      (If more transactions are needed,
997 *                      they are created and destroyed
998 *                      on the fly).
999 */
1000int
1001nfsInit(int smallPoolDepth, int bigPoolDepth)
1002{
1003static int initialised = 0;
1004entry   dummy;
1005rtems_status_code status;
1006
1007        if (initialised)
1008                return 0;
1009
1010        initialised = 1;
1011
1012        fprintf(stderr,
1013          "RTEMS-NFS, " \
1014          "Till Straumann, Stanford/SLAC/SSRL 2002, " \
1015          "See LICENSE file for licensing info.\n");
1016
1017        /* Get a major number */
1018
1019        if (RTEMS_SUCCESSFUL != rtems_io_register_driver(0, &drvNfs, &nfsGlob.nfs_major)) {
1020                fprintf(stderr,"Registering NFS driver failed - %s\n", strerror(errno));
1021                errno = ENOMEM;
1022                return -1;
1023        }
1024
1025        if (0==smallPoolDepth)
1026                smallPoolDepth = 20;
1027        if (0==bigPoolDepth)
1028                bigPoolDepth   = 10;
1029
1030        rtems_recursive_mutex_init(&nfsGlob.llock, "NFSl");
1031        rtems_recursive_mutex_init(&nfsGlob.lock, "NFSm");
1032
1033        /* it's crucial to zero out the 'next' pointer
1034         * because it terminates the xdr_entry recursion
1035         *
1036         * we also must make the filename some non-zero
1037         * char pointer!
1038         */
1039
1040        memset(&dummy, 0, sizeof(dummy));
1041
1042        dummy.nextentry   = 0;
1043        dummy.name        = "somename"; /* guess average length of a filename */
1044        dirres_entry_size = xdr_sizeof((xdrproc_t)xdr_entry, &dummy);
1045
1046        nfsGlob.smallPool = rpcUdpXactPoolCreate(
1047                NFS_PROGRAM,
1048                NFS_VERSION_2,
1049                CONFIG_NFS_SMALL_XACT_SIZE,
1050                smallPoolDepth);
1051        if (nfsGlob.smallPool == NULL) {
1052                goto cleanup;
1053        }
1054
1055        nfsGlob.bigPool = rpcUdpXactPoolCreate(
1056                NFS_PROGRAM,
1057                NFS_VERSION_2,
1058                CONFIG_NFS_BIG_XACT_SIZE,
1059                bigPoolDepth);
1060        if (nfsGlob.bigPool == NULL) {
1061                goto cleanup;
1062        }
1063
1064        if (sizeof(ino_t) < sizeof(u_int)) {
1065                fprintf(stderr,
1066                        "WARNING: Using 'short st_ino' hits performance and may fail to access/find correct files\n");
1067                fprintf(stderr,
1068                        "you should fix newlib's sys/stat.h - for now I'll enable a hack...\n");
1069
1070        }
1071
1072        return 0;
1073
1074cleanup:
1075
1076        nfsCleanup();
1077        initialised = 0;
1078
1079        return -1;
1080}
1081
1082/* Driver cleanup code
1083 */
1084int
1085nfsCleanup(void)
1086{
1087int                     refuse;
1088
1089        LOCK(nfsGlob.llock);
1090        if ( (refuse = nfsGlob.num_mounted_fs) ) {
1091                fprintf(stderr,"Refuse to unload NFS; %i filesystems still mounted.\n",
1092                                                refuse);
1093                nfsMountsShow(stderr);
1094                /* yes, printing is slow - but since you try to unload the driver,
1095                 * you assume nobody is using NFS, so what if they have to wait?
1096                 */
1097                UNLOCK(nfsGlob.llock);
1098                return -1;
1099        }
1100
1101        if (nfsGlob.smallPool != NULL) {
1102                rpcUdpXactPoolDestroy(nfsGlob.smallPool);
1103                nfsGlob.smallPool = NULL;
1104        }
1105
1106        if (nfsGlob.bigPool != NULL) {
1107                rpcUdpXactPoolDestroy(nfsGlob.bigPool);
1108                nfsGlob.bigPool = NULL;
1109        }
1110
1111        if (nfsGlob.nfs_major != 0xffffffff) {
1112                rtems_io_unregister_driver(nfsGlob.nfs_major);
1113                nfsGlob.nfs_major = 0xffffffff;
1114        }
1115
1116        UNLOCK(nfsGlob.llock);
1117
1118        rtems_recursive_mutex_destroy(&nfsGlob.lock);
1119        rtems_recursive_mutex_destroy(&nfsGlob.llock);
1120
1121        return 0;
1122}
1123
1124/* NFS RPC wrapper.
1125 *
1126 * ARGS:        srvr    the NFS server we want to call
1127 *                      proc    the NFSPROC_xx we want to invoke
1128 *                      xargs   xdr routine to wrap the arguments
1129 *                      pargs   pointer to the argument object
1130 *                      xres    xdr routine to unwrap the results
1131 *                      pres    pointer to the result object
1132 *
1133 * RETURNS:     0 on success, -1 on error with errno set.
1134 *
1135 * NOTE:        the caller assumes that errno is set to
1136 *                      a nonzero value if this routine returns
1137 *                      an error (nonzero return value).
1138 *
1139 *                      This routine prints RPC error messages to
1140 *                      stderr.
1141 */
1142STATIC int
1143nfscall(
1144        RpcUdpServer    srvr,
1145        int                             proc,
1146        xdrproc_t               xargs,
1147        void *                  pargs,
1148        xdrproc_t               xres,
1149        void *                  pres)
1150{
1151RpcUdpXact              xact;
1152enum clnt_stat  stat;
1153RpcUdpXactPool  pool;
1154int                             rval = -1;
1155
1156
1157        switch (proc) {
1158                case NFSPROC_SYMLINK:
1159                case NFSPROC_WRITE:
1160                                        pool = nfsGlob.bigPool;         break;
1161                default:        pool = nfsGlob.smallPool;       break;
1162        }
1163
1164        xact = rpcUdpXactPoolGet(pool, XactGetCreate);
1165
1166        if ( !xact ) {
1167                errno = ENOMEM;
1168                return -1;
1169        }
1170
1171        if ( RPC_SUCCESS != (stat=rpcUdpSend(
1172                                                                xact,
1173                                                                srvr,
1174                                                                NFSCALL_TIMEOUT,
1175                                                                proc,
1176                                                                xres,
1177                                                                pres,
1178                                                                xargs,
1179                                                                pargs,
1180                                                                0)) ||
1181             RPC_SUCCESS != (stat=rpcUdpRcv(xact)) ) {
1182
1183                fprintf(stderr,
1184                                "NFS (proc %i) - %s\n",
1185                                proc,
1186                                clnt_sperrno(stat));
1187
1188                switch (stat) {
1189                        /* TODO: this is probably not complete and/or fully accurate */
1190                        case RPC_CANTENCODEARGS : errno = EINVAL;       break;
1191                        case RPC_AUTHERROR      : errno = EPERM;        break;
1192
1193                        case RPC_CANTSEND               :
1194                        case RPC_CANTRECV               : /* hope they have errno set */
1195                        case RPC_SYSTEMERROR    : break;
1196
1197                        default                 : errno = EIO;          break;
1198                }
1199        } else {
1200                rval = 0;
1201        }
1202
1203        /* release the transaction back into the pool */
1204        rpcUdpXactPoolPut(xact);
1205
1206        if (rval && !errno)
1207                errno = EIO;
1208
1209        return rval;
1210}
1211
1212/* Check the 'age' of a node's stats
1213 * and read the attributes from the server
1214 * if necessary.
1215 *
1216 * ARGS:        node    node to update
1217 *                      force   enforce updating ignoring
1218 *                                      the timestamp/age
1219 *
1220 * RETURNS:     0 on success,
1221 *                      -1 on failure with errno set
1222 */
1223
1224static int
1225updateAttr(NfsNode node, int force)
1226{
1227        int rv = 0;
1228
1229        if (force
1230#ifdef CONFIG_ATTR_LIFETIME
1231                || (nowSeconds() - node->age > CONFIG_ATTR_LIFETIME)
1232#endif
1233        ) {
1234                rv = nfscall(
1235                        node->nfs->server,
1236                        NFSPROC_GETATTR,
1237                        (xdrproc_t) xdr_nfs_fh, &SERP_FILE(node),
1238                        (xdrproc_t) xdr_attrstat, &node->serporid
1239                );
1240
1241                if (rv == 0) {
1242                        rv = nfsEvaluateStatus(node->serporid.status);
1243
1244                        if (rv == 0) {
1245                                node->age = nowSeconds();
1246                        }
1247                }
1248        }
1249
1250        return rv;
1251}
1252
1253/*
1254 * IP address helper.
1255 *
1256 * initialize a sockaddr_in from a
1257 * [<uid>'.'<gid>'@']<host>':'<path>" string and let
1258 * pPath point to the <path> part; retrieve the optional
1259 * uid/gids
1260 *
1261 * ARGS:        see description above
1262 *
1263 * RETURNS:     0 on success,
1264 *                      -1 on failure with errno set
1265 */
1266static int
1267buildIpAddr(u_long *puid, u_long *pgid,
1268                        char **pHost, struct sockaddr_in *psa,
1269                        char **pPath)
1270{
1271struct hostent *h;
1272char    host[64];
1273char    *chpt = *pPath;
1274char    *path;
1275int             len;
1276
1277        if ( !chpt ) {
1278                errno = EINVAL;
1279                return -1;
1280        }
1281
1282        /* look for the optional uid/gid */
1283        if ( (chpt = strchr(chpt, UIDSEP)) ) {
1284                if ( 2 != sscanf(*pPath,"%li.%li",puid,pgid) ) {
1285                        errno = EINVAL;
1286                        return -1;
1287                }
1288                chpt++;
1289        } else {
1290                *puid = geteuid();
1291                *pgid = getegid();
1292                chpt  = *pPath;
1293        }
1294        if ( pHost )
1295                *pHost = chpt;
1296
1297        /* split the device name which is in the form
1298         *
1299         * <host> ':' <path>
1300         *
1301         * into its components using a local buffer
1302         */
1303
1304        if ( !(path = strchr(chpt, HOSTDELIM)) ||
1305              (len  = path - chpt) >= sizeof(host) - 1 ) {
1306                errno = EINVAL;
1307                return -1;
1308        }
1309        /* point to path beyond ':' */
1310        path++;
1311
1312        strncpy(host, chpt, len);
1313        host[len]=0;
1314
1315  /* BEGIN OF NON-THREAD SAFE REGION */
1316
1317        h = gethostbyname(host);
1318
1319        if ( !h ) {
1320                errno = EINVAL;
1321                return -1;
1322        }
1323
1324        memcpy(&psa->sin_addr, h->h_addr, sizeof (struct in_addr));
1325
1326  /* END OF NON-THREAD SAFE REGION */
1327
1328        psa->sin_family = AF_INET;
1329        psa->sin_port   = 0;
1330        *pPath          = path;
1331        return 0;
1332}
1333
1334/* wrapper similar to nfscall.
1335 * However, since it is not used
1336 * very often, the simpler and less
1337 * efficient rpcUdpCallRp API is used.
1338 *
1339 * ARGS:        see 'nfscall()' above
1340 *
1341 * RETURNS:     RPC status
1342 */
1343static enum clnt_stat
1344mntcall(
1345        struct sockaddr_in      *psrvr,
1346        int                                     proc,
1347        xdrproc_t                       xargs,
1348        void *                          pargs,
1349        xdrproc_t                       xres,
1350        void *                          pres,
1351        u_long                          uid,
1352        u_long                          gid)
1353{
1354#ifdef MOUNT_V1_PORT
1355int                                     retry;
1356#endif
1357enum clnt_stat          stat = RPC_FAILED;
1358
1359#ifdef MOUNT_V1_PORT
1360        /* if the portmapper fails, retry a fixed port */
1361        for (retry = 1, psrvr->sin_port = 0, stat = RPC_FAILED;
1362                 retry >= 0 && stat;
1363                 stat && (psrvr->sin_port = htons(MOUNT_V1_PORT)), retry-- )
1364#endif
1365                stat  = rpcUdpCallRp(
1366                                                psrvr,
1367                                                MOUNTPROG,
1368                                                MOUNTVERS,
1369                                                proc,
1370                                                xargs,
1371                                                pargs,
1372                                                xres,
1373                                                pres,
1374                                                uid,
1375                                                gid,
1376                                                MNTCALL_TIMEOUT
1377                                );
1378        return stat;
1379}
1380
1381/*****************************************
1382        RTEMS File System Operations for NFS
1383 *****************************************/
1384
1385static bool nfs_is_directory(
1386        rtems_filesystem_eval_path_context_t *ctx,
1387        void *arg
1388)
1389{
1390        bool is_dir = false;
1391        rtems_filesystem_location_info_t *currentloc =
1392                rtems_filesystem_eval_path_get_currentloc(ctx);
1393        NfsNode node = currentloc->node_access;
1394        int force_update = 0;
1395
1396        if (updateAttr(node, force_update) == 0) {
1397                is_dir = SERP_ATTR(node).type == NFDIR;
1398        }
1399
1400        return is_dir;
1401}
1402
1403static int nfs_search_in_directory(
1404        Nfs nfs,
1405        const NfsNode dir,
1406        char *part,
1407        NfsNode entry
1408)
1409{
1410        int rv;
1411
1412        entry->nfs = nfs;
1413
1414        /* lookup one element */
1415        SERP_ATTR(entry) = SERP_ATTR(dir);
1416        SERP_FILE(entry) = SERP_FILE(dir);
1417        SERP_ARGS(entry).diroparg.name = part;
1418
1419        /* remember args / directory fh */
1420        memcpy(&entry->args, &SERP_FILE(dir), sizeof(dir->args));
1421
1422#if DEBUG & DEBUG_EVALPATH
1423        fprintf(stderr,"Looking up '%s'\n",part);
1424#endif
1425
1426        rv = nfscall(
1427                nfs->server,
1428                NFSPROC_LOOKUP,
1429                (xdrproc_t) xdr_diropargs, &SERP_FILE(entry),
1430                (xdrproc_t) xdr_serporid,  &entry->serporid
1431        );
1432
1433        if (rv == 0 && entry->serporid.status == NFS_OK) {
1434                int force_update = 1;
1435
1436                rv = updateAttr(entry, force_update);
1437        } else {
1438                rv = -1;
1439        }
1440
1441        return rv;
1442}
1443
1444static void nfs_eval_follow_link(
1445        rtems_filesystem_eval_path_context_t *ctx,
1446        NfsNode link
1447)
1448{
1449        const size_t len = NFS_MAXPATHLEN + 1;
1450        char *buf = malloc(len);
1451
1452        if (buf != NULL) {
1453                ssize_t rv = nfs_readlink_with_node(link, buf, len);
1454
1455                if (rv >= 0) {
1456                        rtems_filesystem_eval_path_recursive(ctx, buf, (size_t) rv);
1457                } else {
1458                        rtems_filesystem_eval_path_error(ctx, 0);
1459                }
1460
1461                free(buf);
1462        } else {
1463                rtems_filesystem_eval_path_error(ctx, ENOMEM);
1464        }
1465}
1466
1467static void nfs_eval_set_handlers(
1468        rtems_filesystem_eval_path_context_t *ctx,
1469        ftype type
1470)
1471{
1472        rtems_filesystem_location_info_t *currentloc =
1473                rtems_filesystem_eval_path_get_currentloc(ctx);
1474
1475        switch (type) {
1476                case NFDIR:
1477                        currentloc->handlers = &nfs_dir_file_handlers;
1478                        break;
1479                case NFREG:
1480                        currentloc->handlers = &nfs_file_file_handlers;
1481                        break;
1482                case NFLNK:
1483                        currentloc->handlers = &nfs_link_file_handlers;
1484                        break;
1485                default:
1486                        currentloc->handlers = &rtems_filesystem_handlers_default;
1487                        break;
1488        }
1489}
1490
1491static int nfs_move_node(NfsNode dst, const NfsNode src, const char *part)
1492{
1493        int rv = 0;
1494
1495        if (dst->str != NULL) {
1496#if DEBUG & DEBUG_COUNT_NODES
1497                rtems_interrupt_lock_context lock_context;
1498                NFS_GLOBAL_ACQUIRE(&lock_context);
1499                        dst->nfs->stringsInUse--;
1500                NFS_GLOBAL_RELEASE(&lock_context);
1501#endif
1502                free(dst->str);
1503        }
1504
1505        *dst = *src;
1506
1507        dst->str = dst->args.name = strdup(part);
1508        if (dst->str != NULL) {
1509#if DEBUG & DEBUG_COUNT_NODES
1510                rtems_interrupt_lock_context lock_context;
1511                NFS_GLOBAL_ACQUIRE(&lock_context);
1512                        dst->nfs->stringsInUse++;
1513                NFS_GLOBAL_RELEASE(&lock_context);
1514#endif
1515        } else {
1516                rv = -1;
1517        }
1518
1519        return rv;
1520}
1521
1522static rtems_filesystem_eval_path_generic_status nfs_eval_part(
1523        rtems_filesystem_eval_path_context_t *ctx,
1524        char *part
1525)
1526{
1527        rtems_filesystem_eval_path_generic_status status =
1528                RTEMS_FILESYSTEM_EVAL_PATH_GENERIC_DONE;
1529        rtems_filesystem_location_info_t *currentloc =
1530                rtems_filesystem_eval_path_get_currentloc(ctx);
1531        Nfs nfs = currentloc->mt_entry->fs_info;
1532        NfsNode dir = currentloc->node_access;
1533        NfsNodeRec entry;
1534        int rv = nfs_search_in_directory(nfs, dir, part, &entry);
1535
1536        if (rv == 0) {
1537                bool terminal = !rtems_filesystem_eval_path_has_path(ctx);
1538                int eval_flags = rtems_filesystem_eval_path_get_flags(ctx);
1539                bool follow_sym_link = (eval_flags & RTEMS_FS_FOLLOW_SYM_LINK) != 0;
1540                ftype type = SERP_ATTR(&entry).type;
1541
1542                rtems_filesystem_eval_path_clear_token(ctx);
1543
1544                if (type == NFLNK && (follow_sym_link || !terminal)) {
1545                        nfs_eval_follow_link(ctx, &entry);
1546                } else {
1547                        rv = nfs_move_node(dir, &entry, part);
1548                        if (rv == 0) {
1549                                nfs_eval_set_handlers(ctx, type);
1550                                if (!terminal) {
1551                                        status = RTEMS_FILESYSTEM_EVAL_PATH_GENERIC_CONTINUE;
1552                                }
1553                        } else {
1554                                rtems_filesystem_eval_path_error(ctx, ENOMEM);
1555                        }
1556                }
1557        } else {
1558                status = RTEMS_FILESYSTEM_EVAL_PATH_GENERIC_NO_ENTRY;
1559        }
1560
1561        return status;
1562}
1563
1564static rtems_filesystem_eval_path_generic_status nfs_eval_token(
1565        rtems_filesystem_eval_path_context_t *ctx,
1566        void *arg,
1567        const char *token,
1568        size_t tokenlen
1569)
1570{
1571        rtems_filesystem_eval_path_generic_status status =
1572                RTEMS_FILESYSTEM_EVAL_PATH_GENERIC_DONE;
1573
1574        if (rtems_filesystem_is_current_directory(token, tokenlen)) {
1575                rtems_filesystem_eval_path_clear_token(ctx);
1576                if (rtems_filesystem_eval_path_has_path(ctx)) {
1577                        status = RTEMS_FILESYSTEM_EVAL_PATH_GENERIC_CONTINUE;
1578                }
1579        } else {
1580                char *part = nfs_dupname(token, tokenlen);
1581
1582                if (part != NULL) {
1583                        status = nfs_eval_part(ctx, part);
1584                        free(part);
1585                } else {
1586                        rtems_filesystem_eval_path_error(ctx, ENOMEM);
1587                }
1588        }
1589
1590        return status;
1591}
1592
1593static const rtems_filesystem_eval_path_generic_config nfs_eval_config = {
1594        .is_directory = nfs_is_directory,
1595        .eval_token = nfs_eval_token
1596};
1597
1598static void nfs_eval_path(rtems_filesystem_eval_path_context_t *ctx)
1599{
1600        rtems_filesystem_eval_path_generic(ctx, NULL, &nfs_eval_config);
1601}
1602
1603/* create a hard link */
1604
1605static int nfs_link(
1606        const rtems_filesystem_location_info_t *parentloc,
1607        const rtems_filesystem_location_info_t *targetloc,
1608        const char *name,
1609        size_t namelen
1610)
1611{
1612int rv = 0;
1613NfsNode pNode = parentloc->node_access;
1614nfsstat status;
1615NfsNode tNode = targetloc->node_access;
1616char *dupname;
1617
1618        dupname = nfs_dupname(name, namelen);
1619        if (dupname == NULL)
1620                return -1;
1621
1622#if DEBUG & DEBUG_SYSCALLS
1623        fprintf(stderr,"Creating link '%s'\n",dupname);
1624#endif
1625
1626        memcpy(&SERP_ARGS(tNode).linkarg.to.dir,
1627                   &SERP_FILE(pNode),
1628                   sizeof(SERP_FILE(pNode)));
1629
1630        SERP_ARGS(tNode).linkarg.to.name = dupname;
1631
1632        rv = nfscall(
1633                tNode->nfs->server,
1634                NFSPROC_LINK,
1635                (xdrproc_t)xdr_linkargs, &SERP_FILE(tNode),
1636                (xdrproc_t)xdr_nfsstat, &status
1637        );
1638
1639        if (rv == 0) {
1640                rv = nfsEvaluateStatus(status);
1641#if DEBUG & DEBUG_SYSCALLS
1642                if (rv != 0) {
1643                        perror("nfs_link");
1644                }
1645#endif
1646        }
1647
1648        free(dupname);
1649
1650        return rv;
1651
1652}
1653
1654static int nfs_do_unlink(
1655        const rtems_filesystem_location_info_t *parentloc,
1656        const rtems_filesystem_location_info_t *loc,
1657        int                                                               proc
1658)
1659{
1660int rv = 0;
1661nfsstat                 status;
1662NfsNode                 node  = loc->node_access;
1663Nfs                             nfs   = node->nfs;
1664#if DEBUG & DEBUG_SYSCALLS
1665char                    *name = NFSPROC_REMOVE == proc ?
1666                                                        "nfs_unlink" : "nfs_rmdir";
1667#endif
1668
1669        /* The FS generics have determined that pathloc is _not_
1670         * a directory. Hence we may assume that the parent
1671         * is in our NFS.
1672         */
1673
1674#if DEBUG & DEBUG_SYSCALLS
1675        assert( node->args.name == node->str && node->str );
1676
1677        fprintf(stderr,"%s '%s'\n", name, node->args.name);
1678#endif
1679
1680        rv = nfscall(
1681                nfs->server,
1682                proc,
1683                (xdrproc_t)xdr_diropargs, &node->args,
1684                (xdrproc_t)xdr_nfsstat, &status
1685        );
1686
1687        if (rv == 0) {
1688                rv = nfsEvaluateStatus(status);
1689#if DEBUG & DEBUG_SYSCALLS
1690                if (rv != 0) {
1691                        perror(name);
1692                }
1693#endif
1694        }
1695
1696        return rv;
1697}
1698
1699static int nfs_chown(
1700        const rtems_filesystem_location_info_t  *pathloc,       /* IN */
1701        uid_t                                    owner,         /* IN */
1702        gid_t                                    group          /* IN */
1703)
1704{
1705sattr   arg;
1706
1707        arg.uid = owner;
1708        arg.gid = group;
1709
1710        return nfs_sattr(pathloc->node_access, &arg, SATTR_UID | SATTR_GID);
1711
1712}
1713
1714static int nfs_clonenode(rtems_filesystem_location_info_t *loc)
1715{
1716        NfsNode node = loc->node_access;
1717
1718        LOCK(nfsGlob.lock);
1719        node = nfsNodeClone(node);
1720        UNLOCK(nfsGlob.lock);
1721
1722        loc->node_access = node;
1723
1724        return node != NULL ? 0 : -1;
1725}
1726
1727/* Cleanup the FS private info attached to pathloc->node_access */
1728static void nfs_freenode(
1729        const rtems_filesystem_location_info_t      *pathloc       /* IN */
1730)
1731{
1732#if DEBUG & DEBUG_COUNT_NODES
1733Nfs     nfs    = ((NfsNode)pathloc->node_access)->nfs;
1734
1735        /* print counts at entry where they are > 0 so 'nfs' is safe from being destroyed
1736         * and there's no race condition
1737         */
1738        fprintf(stderr,
1739                        "entering freenode, in use count is %i nodes, %i strings\n",
1740                        nfs->nodesInUse,
1741                        nfs->stringsInUse);
1742#endif
1743
1744        nfsNodeDestroy(pathloc->node_access);
1745}
1746
1747/* NOTE/TODO: mounting on top of NFS is not currently supported
1748 *
1749 * Challenge: stateless protocol. It would be possible to
1750 * delete mount points on the server. We would need some sort
1751 * of a 'garbage collector' looking for dead/unreachable
1752 * mount points and unmounting them.
1753 * Also, the path evaluation routine would have to check
1754 * for crossing mount points. Crossing over from one NFS
1755 * into another NFS could probably handled iteratively
1756 * rather than by recursion.
1757 */
1758
1759int rtems_nfs_initialize(
1760  rtems_filesystem_mount_table_entry_t *mt_entry,
1761  const void                           *data
1762)
1763{
1764char                            *host;
1765struct sockaddr_in      saddr;
1766enum clnt_stat          stat;
1767fhstatus                        fhstat;
1768u_long                          uid,gid;
1769#ifdef NFS_V2_PORT
1770int                                     retry;
1771#endif
1772Nfs                                     nfs       = 0;
1773NfsNode                         rootNode  = 0;
1774RpcUdpServer            nfsServer = 0;
1775int                                     e         = -1;
1776char                            *path     = mt_entry->dev;
1777
1778  if (rpcUdpInit () < 0) {
1779    fprintf (stderr, "error: initialising RPC\n");
1780    return -1;
1781  }
1782
1783        if (nfsInit(0, 0) != 0) {
1784                fprintf (stderr, "error: initialising NFS\n");
1785                return -1;
1786        };
1787
1788#if 0
1789        printf("Trying to mount %s on %s\n",path,mntpoint);
1790#endif
1791
1792        if ( buildIpAddr(&uid, &gid, &host, &saddr, &path) )
1793                return -1;
1794
1795#ifdef NFS_V2_PORT
1796        /* if the portmapper fails, retry a fixed port */
1797        for (retry = 1, saddr.sin_port = 0, stat = RPC_FAILED;
1798                 retry >= 0 && stat;
1799                 stat && (saddr.sin_port = htons(NFS_V2_PORT)), retry-- )
1800#endif
1801                stat = rpcUdpServerCreate(
1802                                        &saddr,
1803                                        NFS_PROGRAM,
1804                                        NFS_VERSION_2,
1805                                        uid,
1806                                        gid,
1807                                        &nfsServer
1808                                        );
1809
1810        if ( RPC_SUCCESS != stat ) {
1811                fprintf(stderr,
1812                                "Unable to contact NFS server - invalid port? (%s)\n",
1813                                clnt_sperrno(stat));
1814                e = EPROTONOSUPPORT;
1815                goto cleanup;
1816        }
1817
1818
1819        /* first, try to ping the NFS server by
1820         * calling the NULL proc.
1821         */
1822        if ( nfscall(nfsServer,
1823                                         NFSPROC_NULL,
1824                                         (xdrproc_t)xdr_void, 0,
1825                                         (xdrproc_t)xdr_void, 0) ) {
1826
1827                fputs("NFS Ping ",stderr);
1828                fwrite(host, 1, path-host-1, stderr);
1829                fprintf(stderr," failed: %s\n", strerror(errno));
1830
1831                e = errno ? errno : EIO;
1832                goto cleanup;
1833        }
1834
1835        /* that seemed to work - we now try the
1836         * actual mount
1837         */
1838
1839        /* reuse server address but let the mntcall()
1840         * search for the mountd's port
1841         */
1842        saddr.sin_port = 0;
1843
1844        stat = mntcall( &saddr,
1845                                        MOUNTPROC_MNT,
1846                                        (xdrproc_t)xdr_dirpath,
1847                                        &path,
1848                                        (xdrproc_t)xdr_fhstatus,
1849                                        &fhstat,
1850                                        uid,
1851                                        gid );
1852
1853        if (stat) {
1854                fprintf(stderr,"MOUNT -- %s\n",clnt_sperrno(stat));
1855                if ( e<=0 )
1856                        e = EIO;
1857                goto cleanup;
1858        } else if (NFS_OK != (e=fhstat.fhs_status)) {
1859                fprintf(stderr,"MOUNT: %s\n",strerror(e));
1860                goto cleanup;
1861        }
1862
1863        nfs = nfsCreate(nfsServer);
1864        assert( nfs );
1865        nfsServer = 0;
1866
1867        nfs->uid  = uid;
1868        nfs->gid  = gid;
1869
1870        /* that seemed to work - we now create the root node
1871         * and we also must obtain the root node attributes
1872         */
1873        rootNode = nfsNodeCreate(nfs, &fhstat.fhstatus_u.fhs_fhandle);
1874        assert( rootNode );
1875
1876        if ( updateAttr(rootNode, 1 /* force */) ) {
1877                e = errno;
1878                goto cleanup;
1879        }
1880
1881        /* looks good so far */
1882
1883        mt_entry->mt_fs_root->location.node_access = rootNode;
1884
1885        rootNode = 0;
1886
1887        mt_entry->ops = &nfs_fs_ops;
1888        mt_entry->mt_fs_root->location.handlers  = &nfs_dir_file_handlers;
1889        mt_entry->pathconf_limits_and_options = &nfs_limits_and_options;
1890
1891        LOCK(nfsGlob.llock);
1892                nfsGlob.num_mounted_fs++;
1893                /* allocate a new ID for this FS */
1894                nfs->id = nfsGlob.fs_ids++;
1895        UNLOCK(nfsGlob.llock);
1896
1897        mt_entry->fs_info                                = nfs;
1898        nfs->mt_entry                                    = mt_entry;
1899        nfs = 0;
1900
1901        e = 0;
1902
1903cleanup:
1904        if (nfs)
1905                nfsDestroy(nfs);
1906        if (nfsServer)
1907                rpcUdpServerDestroy(nfsServer);
1908        if (rootNode)
1909                nfsNodeDestroy(rootNode);
1910        if (e)
1911                rtems_set_errno_and_return_minus_one(e);
1912        else
1913                return 0;
1914}
1915
1916/* This op is called when they try to unmount THIS fs */
1917STATIC void nfs_fsunmount_me(
1918        rtems_filesystem_mount_table_entry_t *mt_entry    /* in */
1919)
1920{
1921enum clnt_stat          stat;
1922struct sockaddr_in      saddr;
1923char                    *path = mt_entry->dev;
1924int                     nodesInUse;
1925u_long                  uid,gid;
1926int                     status;
1927
1928LOCK(nfsGlob.llock);
1929        nodesInUse = ((Nfs)mt_entry->fs_info)->nodesInUse;
1930
1931        if (nodesInUse > 1 /* one ref to the root node used by us */) {
1932                UNLOCK(nfsGlob.llock);
1933                fprintf(stderr,
1934                                "Refuse to unmount; there are still %i nodes in use (1 used by us)\n",
1935                                nodesInUse);
1936                rtems_fatal_error_occurred(0xdeadbeef);
1937                return;
1938        }
1939
1940        status = buildIpAddr(&uid, &gid, 0, &saddr, &path);
1941        assert( !status );
1942
1943        stat = mntcall( &saddr,
1944                                        MOUNTPROC_UMNT,
1945                                        (xdrproc_t)xdr_dirpath, &path,
1946                                        (xdrproc_t)xdr_void,     0,
1947                                    uid,
1948                                    gid
1949                                  );
1950
1951        if (stat) {
1952                UNLOCK(nfsGlob.llock);
1953                fprintf(stderr,"NFS UMOUNT -- %s\n", clnt_sperrno(stat));
1954                return;
1955        }
1956
1957        nfsNodeDestroy(mt_entry->mt_fs_root->location.node_access);
1958        mt_entry->mt_fs_root->location.node_access = 0;
1959
1960        nfsDestroy(mt_entry->fs_info);
1961        mt_entry->fs_info = 0;
1962
1963        nfsGlob.num_mounted_fs--;
1964UNLOCK(nfsGlob.llock);
1965}
1966
1967static int nfs_mknod(
1968        const rtems_filesystem_location_info_t *parentloc,
1969        const char *name,
1970        size_t namelen,
1971        mode_t mode,
1972        dev_t dev
1973)
1974{
1975
1976int                                     rv = 0;
1977struct timeval                          now;
1978diropres                                res;
1979NfsNode                                 node = parentloc->node_access;
1980Nfs                                     nfs  = node->nfs;
1981mode_t                                  type = S_IFMT & mode;
1982char                                    *dupname;
1983
1984        if (type != S_IFDIR && type != S_IFREG)
1985                rtems_set_errno_and_return_minus_one(ENOTSUP);
1986
1987        dupname = nfs_dupname(name, namelen);
1988        if (dupname == NULL)
1989                return -1;
1990
1991#if DEBUG & DEBUG_SYSCALLS
1992        fprintf(stderr,"nfs_mknod: creating %s\n", dupname);
1993#endif
1994
1995        rtems_clock_get_tod_timeval(&now);
1996
1997        SERP_ARGS(node).createarg.name                  = dupname;
1998        SERP_ARGS(node).createarg.attributes.mode       = mode;
1999        SERP_ARGS(node).createarg.attributes.uid        = nfs->uid;
2000        SERP_ARGS(node).createarg.attributes.gid        = nfs->gid;
2001        SERP_ARGS(node).createarg.attributes.size       = 0;
2002        SERP_ARGS(node).createarg.attributes.atime.seconds      = now.tv_sec;
2003        SERP_ARGS(node).createarg.attributes.atime.useconds     = now.tv_usec;
2004        SERP_ARGS(node).createarg.attributes.mtime.seconds      = now.tv_sec;
2005        SERP_ARGS(node).createarg.attributes.mtime.useconds     = now.tv_usec;
2006
2007        rv = nfscall(
2008                nfs->server,
2009                (type == S_IFDIR) ? NFSPROC_MKDIR : NFSPROC_CREATE,
2010                (xdrproc_t)xdr_createargs, &SERP_FILE(node),
2011                (xdrproc_t)xdr_diropres, &res
2012        );
2013
2014        if (rv == 0) {
2015                rv = nfsEvaluateStatus(res.status);
2016#if DEBUG & DEBUG_SYSCALLS
2017                if (rv != 0) {
2018                        perror("nfs_mknod");
2019                }
2020#endif
2021        }
2022
2023        free(dupname);
2024
2025        return rv;
2026}
2027
2028static int nfs_rmnod(
2029        const rtems_filesystem_location_info_t *parentloc,
2030        const rtems_filesystem_location_info_t *loc
2031)
2032{
2033        int rv = 0;
2034        NfsNode node  = loc->node_access;
2035        int force_update = 0;
2036
2037        if (updateAttr(node, force_update) == 0) {
2038                int proc = SERP_ATTR(node).type == NFDIR
2039                        ? NFSPROC_RMDIR
2040                                : NFSPROC_REMOVE;
2041
2042                rv = nfs_do_unlink(parentloc, loc, proc);
2043        } else {
2044                rv = -1;
2045        }
2046
2047        return rv;
2048}
2049
2050static int nfs_utime(
2051        const rtems_filesystem_location_info_t  *pathloc, /* IN */
2052        time_t                                   actime,  /* IN */
2053        time_t                                   modtime  /* IN */
2054)
2055{
2056sattr   arg;
2057
2058        /* TODO: add rtems EPOCH - UNIX EPOCH seconds */
2059        arg.atime.seconds  = actime;
2060        arg.atime.useconds = 0;
2061        arg.mtime.seconds  = modtime;
2062        arg.mtime.useconds = 0;
2063
2064        return nfs_sattr(pathloc->node_access, &arg, SATTR_ATIME | SATTR_MTIME);
2065}
2066
2067static int nfs_symlink(
2068        const rtems_filesystem_location_info_t *parentloc,
2069        const char *name,
2070        size_t namelen,
2071        const char *target
2072)
2073{
2074int                                     rv = 0;
2075struct timeval                          now;
2076nfsstat                                 status;
2077NfsNode                                 node = parentloc->node_access;
2078Nfs                                     nfs  = node->nfs;
2079char                                    *dupname;
2080
2081        dupname = nfs_dupname(name, namelen);
2082        if (dupname == NULL)
2083                return -1;
2084
2085#if DEBUG & DEBUG_SYSCALLS
2086        fprintf(stderr,"nfs_symlink: creating %s -> %s\n", dupname, target);
2087#endif
2088
2089        rtems_clock_get_tod_timeval(&now);
2090
2091        SERP_ARGS(node).symlinkarg.name                 = dupname;
2092        SERP_ARGS(node).symlinkarg.to                           = (nfspath) target;
2093
2094        SERP_ARGS(node).symlinkarg.attributes.mode      = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO;
2095        SERP_ARGS(node).symlinkarg.attributes.uid       = nfs->uid;
2096        SERP_ARGS(node).symlinkarg.attributes.gid       = nfs->gid;
2097        SERP_ARGS(node).symlinkarg.attributes.size      = 0;
2098        SERP_ARGS(node).symlinkarg.attributes.atime.seconds  = now.tv_sec;
2099        SERP_ARGS(node).symlinkarg.attributes.atime.useconds = now.tv_usec;
2100        SERP_ARGS(node).symlinkarg.attributes.mtime.seconds  = now.tv_sec;
2101        SERP_ARGS(node).symlinkarg.attributes.mtime.useconds = now.tv_usec;
2102
2103        rv = nfscall(
2104                nfs->server,
2105                NFSPROC_SYMLINK,
2106                (xdrproc_t)xdr_symlinkargs, &SERP_FILE(node),
2107                (xdrproc_t)xdr_nfsstat, &status
2108        );
2109
2110        if (rv == 0) {
2111                rv = nfsEvaluateStatus(status);
2112#if DEBUG & DEBUG_SYSCALLS
2113                perror("nfs_symlink");
2114#endif
2115        }
2116
2117        free(dupname);
2118
2119        return rv;
2120}
2121
2122static ssize_t nfs_readlink_with_node(
2123        NfsNode node,
2124        char *buf,
2125        size_t len
2126)
2127{
2128        ssize_t rv;
2129        Nfs nfs = node->nfs;
2130        readlinkres_strbuf rr;
2131
2132        rr.strbuf.buf = buf;
2133        rr.strbuf.max = len - 1;
2134
2135        rv = nfscall(
2136                nfs->server,
2137                NFSPROC_READLINK,
2138                (xdrproc_t)xdr_nfs_fh, &SERP_FILE(node),
2139                (xdrproc_t)xdr_readlinkres_strbuf, &rr
2140        );
2141
2142        if (rv == 0) {
2143                rv = nfsEvaluateStatus(rr.status);
2144
2145                if (rv == 0) {
2146                        rv = (ssize_t) strlen(rr.strbuf.buf);
2147                } else {
2148#if DEBUG & DEBUG_SYSCALLS
2149                        perror("nfs_readlink_with_node");
2150#endif
2151                }
2152        }
2153
2154        return rv;
2155}
2156
2157static ssize_t nfs_readlink(
2158        const rtems_filesystem_location_info_t *loc,
2159        char *buf,
2160        size_t len
2161)
2162{
2163        NfsNode node = loc->node_access;
2164
2165        return nfs_readlink_with_node(node, buf, len);
2166}
2167
2168static int nfs_rename(
2169        const rtems_filesystem_location_info_t *oldparentloc,
2170        const rtems_filesystem_location_info_t *oldloc,
2171        const rtems_filesystem_location_info_t *newparentloc,
2172        const char *name,
2173        size_t namelen
2174)
2175{
2176        int rv = 0;
2177        char *dupname = nfs_dupname(name, namelen);
2178
2179        if (dupname != NULL) {
2180                NfsNode oldParentNode = oldparentloc->node_access;
2181                NfsNode oldNode = oldloc->node_access;
2182                NfsNode newParentNode = newparentloc->node_access;
2183                Nfs nfs = oldParentNode->nfs;
2184                const nfs_fh *toDirSrc = &SERP_FILE(newParentNode);
2185                nfs_fh *toDirDst = &SERP_ARGS(oldParentNode).renamearg.to.dir;
2186                nfsstat status;
2187
2188                SERP_ARGS(oldParentNode).renamearg.name = oldNode->str;
2189                SERP_ARGS(oldParentNode).renamearg.to.name = dupname;
2190                memcpy(toDirDst, toDirSrc, sizeof(*toDirDst));
2191
2192                rv = nfscall(
2193                        nfs->server,
2194                        NFSPROC_RENAME,
2195                        (xdrproc_t) xdr_renameargs,
2196                        &SERP_FILE(oldParentNode),
2197                        (xdrproc_t) xdr_nfsstat,
2198                        &status
2199                );
2200
2201                if (rv == 0) {
2202                        rv = nfsEvaluateStatus(status);
2203                }
2204
2205                free(dupname);
2206        } else {
2207                rv = -1;
2208        }
2209
2210        return rv;
2211}
2212
2213static void nfs_lock(const rtems_filesystem_mount_table_entry_t *mt_entry)
2214{
2215}
2216
2217static void nfs_unlock(const rtems_filesystem_mount_table_entry_t *mt_entry)
2218{
2219}
2220
2221static bool nfs_are_nodes_equal(
2222        const rtems_filesystem_location_info_t *a,
2223        const rtems_filesystem_location_info_t *b
2224)
2225{
2226        bool equal = false;
2227        NfsNode na = a->node_access;
2228
2229        if (updateAttr(na, 0) == 0) {
2230                NfsNode nb = b->node_access;
2231
2232                if (updateAttr(nb, 0) == 0) {
2233                        equal = SERP_ATTR(na).fileid == SERP_ATTR(nb).fileid
2234                                && SERP_ATTR(na).fsid == SERP_ATTR(nb).fsid;
2235                }
2236        }
2237
2238        return equal;
2239}
2240
2241static int nfs_fchmod(
2242        const rtems_filesystem_location_info_t *loc,
2243        mode_t mode
2244)
2245{
2246sattr   arg;
2247
2248        arg.mode = mode;
2249        return nfs_sattr(loc->node_access, &arg, SATTR_MODE);
2250
2251}
2252
2253const struct _rtems_filesystem_operations_table nfs_fs_ops = {
2254        .lock_h         = nfs_lock,
2255        .unlock_h       = nfs_unlock,
2256        .eval_path_h    = nfs_eval_path,
2257        .link_h         = nfs_link,
2258        .are_nodes_equal_h = nfs_are_nodes_equal,
2259        .mknod_h        = nfs_mknod,
2260        .rmnod_h        = nfs_rmnod,
2261        .fchmod_h       = nfs_fchmod,
2262        .chown_h        = nfs_chown,
2263        .clonenod_h     = nfs_clonenode,
2264        .freenod_h      = nfs_freenode,
2265        .mount_h        = rtems_filesystem_default_mount,
2266        .unmount_h      = rtems_filesystem_default_unmount,
2267        .fsunmount_me_h = nfs_fsunmount_me,
2268        .utime_h        = nfs_utime,
2269        .symlink_h      = nfs_symlink,
2270        .readlink_h     = nfs_readlink,
2271        .rename_h       = nfs_rename,
2272        .statvfs_h      = rtems_filesystem_default_statvfs
2273};
2274
2275/*****************************************
2276        File Handlers
2277
2278        NOTE: the FS generics expect a FS'
2279              evalpath_h() to switch the
2280                  pathloc->handlers according
2281                  to the pathloc/node's file
2282                  type.
2283                  We currently have 'file' and
2284                  'directory' handlers and very
2285                  few 'symlink' handlers.
2286
2287                  The handlers for each type are
2288                  implemented or #defined ZERO
2289                  in a 'nfs_file_xxx',
2290                  'nfs_dir_xxx', 'nfs_link_xxx'
2291                  sequence below this point.
2292
2293                  In some cases, a common handler,
2294                  can be used for all file types.
2295                  It is then simply called
2296                  'nfs_xxx'.
2297 *****************************************/
2298
2299/* stateless NFS protocol makes this trivial */
2300static int nfs_file_open(
2301        rtems_libio_t *iop,
2302        const char    *pathname,
2303        int           oflag,
2304        mode_t        mode
2305)
2306{
2307        return 0;
2308}
2309
2310/* reading directories is not stateless; we must
2311 * remember the last 'read' position, i.e.
2312 * the server 'cookie'. We do manage this information
2313 * attached to the pathinfo.node_access_2.
2314 */
2315static int nfs_dir_open(
2316        rtems_libio_t *iop,
2317        const char    *pathname,
2318        int           oflag,
2319        mode_t        mode
2320)
2321{
2322NfsNode         node = iop->pathinfo.node_access;
2323DirInfo         di;
2324
2325        /* create a readdirargs object and copy the file handle;
2326         * attach to the pathinfo.node_access_2
2327         */
2328
2329        di = (DirInfo) malloc(sizeof(*di));
2330        iop->pathinfo.node_access_2 = di;
2331
2332        if ( !di  ) {
2333                errno = ENOMEM;
2334                return -1;
2335        }
2336
2337        memcpy( &di->readdirargs.dir,
2338                        &SERP_FILE(node),
2339                        sizeof(di->readdirargs.dir) );
2340
2341        /* rewind cookie */
2342        memset( &di->readdirargs.cookie,
2343                0,
2344                sizeof(di->readdirargs.cookie) );
2345
2346        di->eofreached = FALSE;
2347
2348        return 0;
2349}
2350
2351static int nfs_file_close(
2352        rtems_libio_t *iop
2353)
2354{
2355        return 0;
2356}
2357
2358static int nfs_dir_close(
2359        rtems_libio_t *iop
2360)
2361{
2362        free(iop->pathinfo.node_access_2);
2363        iop->pathinfo.node_access_2 = 0;
2364        return 0;
2365}
2366
2367static ssize_t nfs_file_read_chunk(
2368        NfsNode node,
2369        uint32_t offset,
2370        void *buffer,
2371        size_t count
2372)
2373{
2374ssize_t rv;
2375readres rr;
2376Nfs             nfs  = node->nfs;
2377
2378        SERP_ARGS(node).readarg.offset          = offset;
2379        SERP_ARGS(node).readarg.count           = count;
2380        SERP_ARGS(node).readarg.totalcount      = UINT32_C(0xdeadbeef);
2381
2382        rr.readres_u.reply.data.data_val        = buffer;
2383
2384        rv = nfscall(
2385                nfs->server,
2386                NFSPROC_READ,
2387                (xdrproc_t)xdr_readargs, &SERP_FILE(node),
2388                (xdrproc_t)xdr_readres, &rr
2389        );
2390
2391        if (rv == 0) {
2392                rv = nfsEvaluateStatus(rr.status);
2393
2394                if (rv == 0) {
2395                        rv = rr.readres_u.reply.data.data_len;
2396
2397#if DEBUG & DEBUG_SYSCALLS
2398                        fprintf(stderr,
2399                                "Read %i (asked for %i) bytes from offset %i to 0x%08x\n",
2400                                rr.readres_u.reply.data.data_len,
2401                                count,
2402                                iop->offset,
2403                                rr.readres_u.reply.data.data_val);
2404#endif
2405                }
2406        }
2407
2408        return rv;
2409}
2410
2411static ssize_t nfs_file_read(
2412        rtems_libio_t *iop,
2413        void *buffer,
2414        size_t count
2415)
2416{
2417        ssize_t rv = 0;
2418        NfsNode node = iop->pathinfo.node_access;
2419        uint32_t offset = iop->offset;
2420        char *in = buffer;
2421
2422        if (iop->offset < 0) {
2423                errno = EINVAL;
2424                return -1;
2425        }
2426
2427        if ((uintmax_t) iop->offset >= UINT32_MAX) {
2428                errno = EFBIG;
2429                return -1;
2430        }
2431
2432        if (count > UINT32_MAX - offset) {
2433                count = UINT32_MAX - offset;
2434        }
2435
2436        do {
2437                size_t chunk = count <= NFS_MAXDATA ? count : NFS_MAXDATA;
2438                ssize_t done = nfs_file_read_chunk(node, offset, in, chunk);
2439
2440                if (done > 0) {
2441                        offset += (uint32_t) done;
2442                        in += done;
2443                        count -= (size_t) done;
2444                        rv += done;
2445                } else {
2446                        count = 0;
2447                        if (done < 0) {
2448                                rv = -1;
2449                        }
2450                }
2451        } while (count > 0);
2452
2453        if (rv > 0) {
2454                iop->offset = offset;
2455        }
2456
2457        return rv;
2458}
2459
2460/* this is called by readdir() / getdents() */
2461static ssize_t nfs_dir_read(
2462        rtems_libio_t *iop,
2463        void          *buffer,
2464        size_t        count
2465)
2466{
2467ssize_t rv;
2468DirInfo                 di     = iop->pathinfo.node_access_2;
2469RpcUdpServer    server = ((Nfs)iop->pathinfo.mt_entry->fs_info)->server;
2470
2471        if ( di->eofreached )
2472                return 0;
2473
2474        di->ptr = di->buf = buffer;
2475
2476        /* align + round down the buffer */
2477        count &= ~ (DIRENT_HEADER_SIZE - 1);
2478        di->len = count;
2479
2480#if 0
2481        /* now estimate the number of entries we should ask for */
2482        count /= DIRENT_HEADER_SIZE + CONFIG_AVG_NAMLEN;
2483
2484        /* estimate the encoded size that might take up */
2485        count *= dirres_entry_size + CONFIG_AVG_NAMLEN;
2486#else
2487        /* integer arithmetics are better done the other way round */
2488        count *= dirres_entry_size + CONFIG_AVG_NAMLEN;
2489        count /= DIRENT_HEADER_SIZE + CONFIG_AVG_NAMLEN;
2490#endif
2491
2492        if (count > NFS_MAXDATA)
2493                count = NFS_MAXDATA;
2494
2495        di->readdirargs.count = count;
2496
2497#if DEBUG & DEBUG_READDIR
2498        fprintf(stderr,
2499                        "Readdir: asking for %i XDR bytes, buffer is %i\n",
2500                        count, di->len);
2501#endif
2502
2503        rv = nfscall(
2504                server,
2505                NFSPROC_READDIR,
2506                (xdrproc_t)xdr_readdirargs, &di->readdirargs,
2507                (xdrproc_t)xdr_dir_info, di
2508        );
2509
2510        if (rv == 0) {
2511                rv = nfsEvaluateStatus(di->status);
2512
2513                if (rv == 0) {
2514                        rv = (char*)di->ptr - (char*)buffer;
2515                }
2516        }
2517
2518        return rv;
2519}
2520
2521static ssize_t nfs_file_write(
2522        rtems_libio_t *iop,
2523        const void    *buffer,
2524        size_t        count
2525)
2526{
2527ssize_t rv;
2528NfsNode         node = iop->pathinfo.node_access;
2529Nfs                     nfs  = node->nfs;
2530
2531        if (count > NFS_MAXDATA)
2532                count = NFS_MAXDATA;
2533
2534
2535        SERP_ARGS(node).writearg.beginoffset = UINT32_C(0xdeadbeef);
2536        if (rtems_libio_iop_is_append(iop)) {
2537                if ( updateAttr(node, 0) ) {
2538                        return -1;
2539                }
2540                if (SERP_ATTR(node).size >= UINT32_MAX) {
2541                        errno = EFBIG;
2542                        return -1;
2543                }
2544                SERP_ARGS(node).writearg.offset = SERP_ATTR(node).size;
2545        } else {
2546                if (iop->offset < 0) {
2547                        errno = EINVAL;
2548                        return -1;
2549                }
2550                if ((uintmax_t) iop->offset >= UINT32_MAX) {
2551                        errno = EFBIG;
2552                        return -1;
2553                }
2554                SERP_ARGS(node).writearg.offset = iop->offset;
2555        }
2556
2557        if (count > UINT32_MAX - SERP_ARGS(node).writearg.offset) {
2558                count = UINT32_MAX - SERP_ARGS(node).writearg.offset;
2559        }
2560
2561        SERP_ARGS(node).writearg.totalcount        = UINT32_C(0xdeadbeef);
2562        SERP_ARGS(node).writearg.data.data_len = count;
2563        SERP_ARGS(node).writearg.data.data_val = (void*)buffer;
2564
2565        /* write XDR buffer size will be chosen by nfscall based
2566         * on the PROC specifier
2567         */
2568
2569        rv = nfscall(
2570                nfs->server,
2571                NFSPROC_WRITE,
2572                (xdrproc_t)xdr_writeargs, &SERP_FILE(node),
2573                (xdrproc_t)xdr_attrstat, &node->serporid
2574        );
2575
2576        if (rv == 0) {
2577                rv = nfsEvaluateStatus(node->serporid.status);
2578
2579                if (rv == 0) {
2580                        node->age = nowSeconds();
2581
2582                        iop->offset += count;
2583                        rv = count;
2584                } else {
2585                        /* try at least to recover the current attributes */
2586                        updateAttr(node, 1 /* force */);
2587                }
2588        }
2589
2590        return rv;
2591}
2592
2593static off_t nfs_dir_lseek(
2594        rtems_libio_t *iop,
2595        off_t          length,
2596        int            whence
2597)
2598{
2599        off_t rv = rtems_filesystem_default_lseek_directory(iop, length, whence);
2600
2601        if (rv == 0) {
2602                DirInfo di = iop->pathinfo.node_access_2;
2603                nfscookie *cookie = &di->readdirargs.cookie;
2604
2605                di->eofreached = FALSE;
2606
2607                /* rewind cookie */
2608                memset(cookie, 0, sizeof(*cookie));
2609        }
2610
2611        return rv;
2612}
2613
2614#if 0   /* structure types for reference */
2615struct fattr {
2616                ftype type;
2617                u_int mode;
2618                u_int nlink;
2619                u_int uid;
2620                u_int gid;
2621                u_int size;
2622                u_int blocksize;
2623                u_int rdev;
2624                u_int blocks;
2625                u_int fsid;
2626                u_int fileid;
2627                nfstime atime;
2628                nfstime mtime;
2629                nfstime ctime;
2630};
2631
2632struct  stat
2633{
2634                dev_t         st_dev;
2635                ino_t         st_ino;
2636                mode_t        st_mode;
2637                nlink_t       st_nlink;
2638                uid_t         st_uid;
2639                gid_t         st_gid;
2640                dev_t         st_rdev;
2641                off_t         st_size;
2642                /* SysV/sco doesn't have the rest... But Solaris, eabi does.  */
2643#if defined(__svr4__) && !defined(__PPC__) && !defined(__sun__)
2644                time_t        st_atime;
2645                time_t        st_mtime;
2646                time_t        st_ctime;
2647#else
2648                time_t        st_atime;
2649                long          st_spare1;
2650                time_t        st_mtime;
2651                long          st_spare2;
2652                time_t        st_ctime;
2653                long          st_spare3;
2654                long          st_blksize;
2655                long          st_blocks;
2656                long      st_spare4[2];
2657#endif
2658};
2659#endif
2660
2661/* common for file/dir/link */
2662static int nfs_fstat(
2663        const rtems_filesystem_location_info_t *loc,
2664        struct stat *buf
2665)
2666{
2667NfsNode node = loc->node_access;
2668fattr   *fa  = &SERP_ATTR(node);
2669
2670        if (updateAttr(node, 0 /* only if old */)) {
2671                return -1;
2672        }
2673
2674/* done by caller
2675        memset(buf, 0, sizeof(*buf));
2676 */
2677
2678        /* translate */
2679
2680        /* one of the branches hopefully is optimized away */
2681        if (sizeof(ino_t) < sizeof(u_int)) {
2682        buf->st_dev             = NFS_MAKE_DEV_T_INO_HACK((NfsNode)loc->node_access);
2683        } else {
2684        buf->st_dev             = NFS_MAKE_DEV_T((NfsNode)loc->node_access);
2685        }
2686        buf->st_mode    = fa->mode;
2687        buf->st_nlink   = fa->nlink;
2688        buf->st_uid             = fa->uid;
2689        buf->st_gid             = fa->gid;
2690        buf->st_size    = fa->size;
2691        /* Set to "preferred size" of this NFS client implementation */
2692        buf->st_blksize = nfsStBlksize ? nfsStBlksize : fa->blocksize;
2693        buf->st_rdev    = fa->rdev;
2694        buf->st_blocks  = fa->blocks;
2695        buf->st_ino     = fa->fileid;
2696        buf->st_atime   = fa->atime.seconds;
2697        buf->st_mtime   = fa->mtime.seconds;
2698        buf->st_ctime   = fa->ctime.seconds;
2699
2700#if 0 /* NFS should return the modes */
2701        switch(fa->type) {
2702                default:
2703                case NFNON:
2704                case NFBAD:
2705                                break;
2706
2707                case NFSOCK: buf->st_mode |= S_IFSOCK; break;
2708                case NFFIFO: buf->st_mode |= S_IFIFO;  break;
2709                case NFREG : buf->st_mode |= S_IFREG;  break;
2710                case NFDIR : buf->st_mode |= S_IFDIR;  break;
2711                case NFBLK : buf->st_mode |= S_IFBLK;  break;
2712                case NFCHR : buf->st_mode |= S_IFCHR;  break;
2713                case NFLNK : buf->st_mode |= S_IFLNK;  break;
2714        }
2715#endif
2716
2717        return 0;
2718}
2719
2720/* a helper which does the real work for
2721 * a couple of handlers (such as chmod,
2722 * ftruncate or utime)
2723 */
2724static int
2725nfs_sattr(NfsNode node, sattr *arg, u_long mask)
2726{
2727int rv;
2728struct timeval                          now;
2729nfstime                                 nfsnow, t;
2730u_int                                   mode;
2731
2732        if (updateAttr(node, 0 /* only if old */))
2733                return -1;
2734
2735        rtems_clock_get_tod_timeval(&now);
2736
2737        /* TODO: add rtems EPOCH - UNIX EPOCH seconds */
2738        nfsnow.seconds  = now.tv_sec;
2739        nfsnow.useconds = now.tv_usec;
2740
2741        /* merge permission bits into existing type bits */
2742        mode = SERP_ATTR(node).mode;
2743        if (mask & SATTR_MODE) {
2744                mode &= S_IFMT;
2745                mode |= arg->mode & ~S_IFMT;
2746        } else {
2747                mode = -1;
2748        }
2749        SERP_ARGS(node).sattrarg.attributes.mode  = mode;
2750
2751        SERP_ARGS(node).sattrarg.attributes.uid   =
2752                (mask & SATTR_UID)  ? arg->uid : -1;
2753
2754        SERP_ARGS(node).sattrarg.attributes.gid   =
2755                (mask & SATTR_GID)  ? arg->gid : -1;
2756
2757        SERP_ARGS(node).sattrarg.attributes.size  =
2758                (mask & SATTR_SIZE) ? arg->size : -1;
2759
2760        if (mask & SATTR_ATIME)
2761                t = arg->atime;
2762        else if (mask & SATTR_TOUCHA)
2763                t = nfsnow;
2764        else
2765                t.seconds = t.useconds = -1;
2766        SERP_ARGS(node).sattrarg.attributes.atime = t;
2767
2768        if (mask & SATTR_ATIME)
2769                t = arg->mtime;
2770        else if (mask & SATTR_TOUCHA)
2771                t = nfsnow;
2772        else
2773                t.seconds = t.useconds = -1;
2774        SERP_ARGS(node).sattrarg.attributes.mtime = t;
2775
2776        node->serporid.status = NFS_OK;
2777
2778        rv = nfscall(
2779                node->nfs->server,
2780                NFSPROC_SETATTR,
2781                (xdrproc_t)xdr_sattrargs, &SERP_FILE(node),
2782                (xdrproc_t)xdr_attrstat, &node->serporid
2783        );
2784
2785        if (rv == 0) {
2786                rv = nfsEvaluateStatus(node->serporid.status);
2787
2788                if (rv == 0) {
2789                        node->age = nowSeconds();
2790                } else {
2791#if DEBUG & DEBUG_SYSCALLS
2792                        fprintf(stderr,"nfs_sattr: %s\n",strerror(errno));
2793#endif
2794                        /* try at least to recover the current attributes */
2795                        updateAttr(node, 1 /* force */);
2796                }
2797        } else {
2798#if DEBUG & DEBUG_SYSCALLS
2799                fprintf(stderr,
2800                                "nfs_sattr (mask 0x%08x): %s",
2801                                mask,
2802                                strerror(errno));
2803#endif
2804        }
2805
2806        return rv;
2807}
2808
2809/* just set the size attribute to 'length'
2810 * the server will take care of the rest :-)
2811 */
2812static int nfs_file_ftruncate(
2813        rtems_libio_t *iop,
2814        off_t          length
2815)
2816{
2817sattr                                   arg;
2818
2819        if (length < 0) {
2820                errno = EINVAL;
2821                return -1;
2822        }
2823
2824        if ((uintmax_t) length > UINT32_MAX) {
2825                errno = EFBIG;
2826                return -1;
2827        }
2828
2829        arg.size = length;
2830        /* must not modify any other attribute; if we are not the owner
2831         * of the file or directory but only have write access changing
2832         * any attribute besides 'size' will fail...
2833         */
2834        return nfs_sattr(iop->pathinfo.node_access,
2835                                         &arg,
2836                                         SATTR_SIZE);
2837}
2838
2839/* the file handlers table */
2840static const
2841struct _rtems_filesystem_file_handlers_r nfs_file_file_handlers = {
2842        .open_h      = nfs_file_open,
2843        .close_h     = nfs_file_close,
2844        .read_h      = nfs_file_read,
2845        .write_h     = nfs_file_write,
2846        .ioctl_h     = rtems_filesystem_default_ioctl,
2847        .lseek_h     = rtems_filesystem_default_lseek_file,
2848        .fstat_h     = nfs_fstat,
2849        .ftruncate_h = nfs_file_ftruncate,
2850        .fsync_h     = rtems_filesystem_default_fsync_or_fdatasync,
2851        .fdatasync_h = rtems_filesystem_default_fsync_or_fdatasync,
2852        .fcntl_h     = rtems_filesystem_default_fcntl,
2853        .kqfilter_h  = rtems_filesystem_default_kqfilter,
2854        .mmap_h      = rtems_filesystem_default_mmap,
2855        .poll_h      = rtems_filesystem_default_poll,
2856        .readv_h     = rtems_filesystem_default_readv,
2857        .writev_h    = rtems_filesystem_default_writev
2858};
2859
2860/* the directory handlers table */
2861static const
2862struct _rtems_filesystem_file_handlers_r nfs_dir_file_handlers = {
2863        .open_h      = nfs_dir_open,
2864        .close_h     = nfs_dir_close,
2865        .read_h      = nfs_dir_read,
2866        .write_h     = rtems_filesystem_default_write,
2867        .ioctl_h     = rtems_filesystem_default_ioctl,
2868        .lseek_h     = nfs_dir_lseek,
2869        .fstat_h     = nfs_fstat,
2870        .ftruncate_h = rtems_filesystem_default_ftruncate_directory,
2871        .fsync_h     = rtems_filesystem_default_fsync_or_fdatasync,
2872        .fdatasync_h = rtems_filesystem_default_fsync_or_fdatasync,
2873        .fcntl_h     = rtems_filesystem_default_fcntl,
2874        .kqfilter_h  = rtems_filesystem_default_kqfilter,
2875        .mmap_h      = rtems_filesystem_default_mmap,
2876        .poll_h      = rtems_filesystem_default_poll,
2877        .readv_h     = rtems_filesystem_default_readv,
2878        .writev_h    = rtems_filesystem_default_writev
2879};
2880
2881/* the link handlers table */
2882static const
2883struct _rtems_filesystem_file_handlers_r nfs_link_file_handlers = {
2884        .open_h      = rtems_filesystem_default_open,
2885        .close_h     = rtems_filesystem_default_close,
2886        .read_h      = rtems_filesystem_default_read,
2887        .write_h     = rtems_filesystem_default_write,
2888        .ioctl_h     = rtems_filesystem_default_ioctl,
2889        .lseek_h     = rtems_filesystem_default_lseek,
2890        .fstat_h     = nfs_fstat,
2891        .ftruncate_h = rtems_filesystem_default_ftruncate,
2892        .fsync_h     = rtems_filesystem_default_fsync_or_fdatasync,
2893        .fdatasync_h = rtems_filesystem_default_fsync_or_fdatasync,
2894        .fcntl_h     = rtems_filesystem_default_fcntl,
2895        .kqfilter_h  = rtems_filesystem_default_kqfilter,
2896        .mmap_h      = rtems_filesystem_default_mmap,
2897        .poll_h      = rtems_filesystem_default_poll,
2898        .readv_h     = rtems_filesystem_default_readv,
2899        .writev_h    = rtems_filesystem_default_writev
2900};
2901
2902/* we need a dummy driver entry table to get a
2903 * major number from the system
2904 */
2905static
2906rtems_device_driver nfs_initialize(
2907                rtems_device_major_number       major,
2908                rtems_device_minor_number       minor,
2909                void                                            *arg
2910)
2911{
2912        /* we don't really use this routine because
2913     * we cannot supply an argument (contrary
2914     * to what the 'arg' parameter suggests - it
2915     * is always set to 0 by the generics :-()
2916     * and because we don't want the user to
2917     * have to deal with the major number (which
2918     * OTOH is something WE are interested in. The
2919     * only reason for using this API was getting
2920     * a major number, after all).
2921     *
2922         * Something must be present, however, to
2923         * reserve a slot in the driver table.
2924         */
2925        return RTEMS_SUCCESSFUL;
2926}
2927
2928static rtems_driver_address_table       drvNfs = {
2929                nfs_initialize,
2930                0,                                      /* open    */
2931                0,                                      /* close   */
2932                0,                                      /* read    */
2933                0,                                      /* write   */
2934                0                                       /* control */
2935};
2936
2937/* Dump a list of the currently mounted NFS to a  file */
2938int
2939nfsMountsShow(FILE *f)
2940{
2941char    *mntpt = 0;
2942Nfs             nfs;
2943
2944        if (!f)
2945                f = stdout;
2946
2947        if ( !(mntpt=malloc(MAXPATHLEN)) ) {
2948                fprintf(stderr,"nfsMountsShow(): no memory\n");
2949                return -1;
2950        }
2951
2952        fprintf(f,"Currently Mounted NFS:\n");
2953
2954        LOCK(nfsGlob.llock);
2955
2956        for (nfs = nfsGlob.mounted_fs; nfs; nfs=nfs->next) {
2957                fprintf(f,"%s on ", nfs->mt_entry->dev);
2958                if (rtems_filesystem_resolve_location(mntpt, MAXPATHLEN, &nfs->mt_entry->mt_fs_root->location))
2959                        fprintf(f,"<UNABLE TO LOOKUP MOUNTPOINT>\n");
2960                else
2961                        fprintf(f,"%s\n",mntpt);
2962        }
2963
2964        UNLOCK(nfsGlob.llock);
2965
2966        free(mntpt);
2967        return 0;
2968}
2969
2970#if 0
2971CCJ_REMOVE_MOUNT
2972/* convenience wrapper
2973 *
2974 * NOTE: this routine calls NON-REENTRANT
2975 *       gethostbyname() if the host is
2976 *       not in 'dot' notation.
2977 */
2978int
2979nfsMount(char *uidhost, char *path, char *mntpoint)
2980{
2981struct stat                                                             st;
2982int                                                                             devl;
2983char                                                                    *host;
2984int                                                                             rval = -1;
2985char                                                                    *dev =  0;
2986
2987        if (!uidhost || !path || !mntpoint) {
2988                fprintf(stderr,"usage: nfsMount(""[uid.gid@]host"",""path"",""mountpoint"")\n");
2989                nfsMountsShow(stderr);
2990                return -1;
2991        }
2992
2993        if ( !(dev = malloc((devl=strlen(uidhost) + 20 + strlen(path)+1))) ) {
2994                fprintf(stderr,"nfsMount: out of memory\n");
2995                return -1;
2996        }
2997
2998        /* Try to create the mount point if nonexistent */
2999        if (stat(mntpoint, &st)) {
3000                if (ENOENT != errno) {
3001                        perror("nfsMount trying to create mount point - stat failed");
3002                        goto cleanup;
3003                } else if (mkdir(mntpoint,0777)) {
3004                        perror("nfsMount trying to create mount point");
3005                        goto cleanup;
3006                }
3007        }
3008
3009        if ( !(host=strchr(uidhost,UIDSEP)) ) {
3010                host = uidhost;
3011        } else {
3012                host++;
3013        }
3014
3015        if (isdigit((unsigned char)*host)) {
3016                /* avoid using gethostbyname */
3017                sprintf(dev,"%s:%s",uidhost,path);
3018        } else {
3019                struct hostent *h;
3020
3021                /* copy the uid part (hostname will be
3022                 * overwritten)
3023                 */
3024                strcpy(dev, uidhost);
3025
3026                /* NOTE NOTE NOTE: gethostbyname is NOT
3027                 * thread safe. This is UGLY
3028                 */
3029
3030/* BEGIN OF NON-THREAD SAFE REGION */
3031
3032                h = gethostbyname(host);
3033
3034                if ( !h ||
3035                         !inet_ntop( AF_INET,
3036                                             (struct in_addr*)h->h_addr_list[0],
3037                                                 dev  + (host - uidhost),
3038                                                 devl - (host - uidhost) )
3039                        ) {
3040                        fprintf(stderr,"nfsMount: host '%s' not found\n",host);
3041                        goto cleanup;
3042                }
3043
3044/* END OF NON-THREAD SAFE REGION */
3045
3046                /* append ':<path>' */
3047                strcat(dev,":");
3048                strcat(dev,path);
3049        }
3050
3051        printf("Trying to mount %s on %s\n",dev,mntpoint);
3052
3053        if (mount(dev,
3054                          mntpoint,
3055                          "nfs",
3056                          RTEMS_FILESYSTEM_READ_WRITE,
3057                          NULL)) {
3058                perror("nfsMount - mount");
3059                goto cleanup;
3060        }
3061
3062        rval = 0;
3063
3064cleanup:
3065        free(dev);
3066        return rval;
3067}
3068#endif
3069
3070/* HERE COMES A REALLY UGLY HACK */
3071
3072/* This is stupid; it is _very_ hard to find the path
3073 * leading to a rtems_filesystem_location_info_t node :-(
3074 * The only easy way is making the location the current
3075 * directory and issue a getcwd().
3076 * However, since we don't want to tamper with the
3077 * current directory, we must create a separate
3078 * task to do the job for us - sigh.
3079 */
3080
3081typedef struct ResolvePathArgRec_ {
3082        rtems_filesystem_location_info_t        *loc;   /* IN: location to resolve      */
3083        char                                                            *buf;   /* IN/OUT: buffer where to put the path */
3084        int                                                                     len;    /* IN: buffer length            */
3085        rtems_binary_semaphore                  sync;   /* IN: synchronization          */
3086        rtems_status_code                                       status; /* OUT: result                          */
3087} ResolvePathArgRec, *ResolvePathArg;
3088
3089static void
3090resolve_path(rtems_task_argument arg)
3091{
3092ResolvePathArg                                          rpa = (ResolvePathArg)arg;
3093rtems_filesystem_location_info_t        old;
3094
3095        /* IMPORTANT: let the helper task have its own libio environment (i.e. cwd) */
3096        if (RTEMS_SUCCESSFUL == (rpa->status = rtems_libio_set_private_env())) {
3097
3098                old = rtems_filesystem_current->location;
3099
3100                rtems_filesystem_current->location = *(rpa->loc);
3101
3102                if ( !getcwd(rpa->buf, rpa->len) )
3103                        rpa->status = RTEMS_UNSATISFIED;
3104
3105                /* must restore the cwd because 'freenode' will be called on it */
3106                rtems_filesystem_current->location = old;
3107        }
3108        rtems_binary_semaphore_post(&rpa->sync);
3109        rtems_task_delete(RTEMS_SELF);
3110}
3111
3112
3113/* a utility routine to find the path leading to a
3114 * rtems_filesystem_location_info_t node
3115 *
3116 * INPUT: 'loc' and a buffer 'buf' (length 'len') to hold the
3117 *        path.
3118 * OUTPUT: path copied into 'buf'
3119 *
3120 * RETURNS: 0 on success, RTEMS error code on error.
3121 */
3122rtems_status_code
3123rtems_filesystem_resolve_location(char *buf, int len, rtems_filesystem_location_info_t *loc)
3124{
3125ResolvePathArgRec       arg;
3126rtems_id                        tid = 0;
3127rtems_task_priority     pri;
3128rtems_status_code       status;
3129
3130        arg.loc  = loc;
3131        arg.buf  = buf;
3132        arg.len  = len;
3133
3134        rtems_binary_semaphore_init(&arg.sync, "NFSress");
3135
3136        rtems_task_set_priority(RTEMS_SELF, RTEMS_CURRENT_PRIORITY, &pri);
3137
3138        status = rtems_task_create(
3139                                        rtems_build_name('r','e','s','s'),
3140                                        pri,
3141                                        RTEMS_MINIMUM_STACK_SIZE + 50000,
3142                                        RTEMS_DEFAULT_MODES,
3143                                        RTEMS_DEFAULT_ATTRIBUTES,
3144                                        &tid);
3145
3146        if (RTEMS_SUCCESSFUL != status)
3147                goto cleanup;
3148
3149        status = rtems_task_start(tid, resolve_path, (rtems_task_argument)&arg);
3150
3151        if (RTEMS_SUCCESSFUL != status) {
3152                rtems_task_delete(tid);
3153                goto cleanup;
3154        }
3155
3156
3157        /* synchronize with the helper task */
3158        rtems_binary_semaphore_wait(&arg.sync);
3159
3160        status = arg.status;
3161
3162cleanup:
3163        rtems_binary_semaphore_destroy(&arg.sync);
3164
3165        return status;
3166}
3167
3168int
3169nfsSetTimeout(uint32_t timeout_ms)
3170{
3171rtems_interrupt_lock_context lock_context;
3172uint32_t                  s,us;
3173
3174        if ( timeout_ms > 100000 ) {
3175                /* out of range */
3176                return -1;
3177        }
3178
3179        s  = timeout_ms/1000;
3180        us = (timeout_ms % 1000) * 1000;
3181
3182        NFS_GLOBAL_ACQUIRE(&lock_context);
3183        _nfscalltimeout.tv_sec  = s;
3184        _nfscalltimeout.tv_usec = us;
3185        NFS_GLOBAL_RELEASE(&lock_context);
3186
3187        return 0;
3188}
3189
3190uint32_t
3191nfsGetTimeout( void )
3192{
3193rtems_interrupt_lock_context lock_context;
3194uint32_t              s,us;
3195        NFS_GLOBAL_ACQUIRE(&lock_context);
3196        s  = _nfscalltimeout.tv_sec;
3197        us = _nfscalltimeout.tv_usec;
3198        NFS_GLOBAL_RELEASE(&lock_context);
3199        return s*1000 + us/1000;
3200}
Note: See TracBrowser for help on using the repository browser.