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

5
Last change on this file since f004b2b8 was f004b2b8, checked in by Sebastian Huber <sebastian.huber@…>, on 10/02/18 at 08:22:15

Use rtems_task_exit()

Update #3530.
Update #3533.

  • 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 "../proto/nfs_prot.h"
84#include "../proto/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;
1005
1006        if (initialised)
1007                return 0;
1008
1009        initialised = 1;
1010
1011        fprintf(stderr,
1012          "RTEMS-NFS, " \
1013          "Till Straumann, Stanford/SLAC/SSRL 2002, " \
1014          "See LICENSE file for licensing info.\n");
1015
1016        /* Get a major number */
1017
1018        if (RTEMS_SUCCESSFUL != rtems_io_register_driver(0, &drvNfs, &nfsGlob.nfs_major)) {
1019                fprintf(stderr,"Registering NFS driver failed - %s\n", strerror(errno));
1020                errno = ENOMEM;
1021                return -1;
1022        }
1023
1024        if (0==smallPoolDepth)
1025                smallPoolDepth = 20;
1026        if (0==bigPoolDepth)
1027                bigPoolDepth   = 10;
1028
1029        rtems_recursive_mutex_init(&nfsGlob.llock, "NFSl");
1030        rtems_recursive_mutex_init(&nfsGlob.lock, "NFSm");
1031
1032        /* it's crucial to zero out the 'next' pointer
1033         * because it terminates the xdr_entry recursion
1034         *
1035         * we also must make the filename some non-zero
1036         * char pointer!
1037         */
1038
1039        memset(&dummy, 0, sizeof(dummy));
1040
1041        dummy.nextentry   = 0;
1042        dummy.name        = "somename"; /* guess average length of a filename */
1043        dirres_entry_size = xdr_sizeof((xdrproc_t)xdr_entry, &dummy);
1044
1045        nfsGlob.smallPool = rpcUdpXactPoolCreate(
1046                NFS_PROGRAM,
1047                NFS_VERSION_2,
1048                CONFIG_NFS_SMALL_XACT_SIZE,
1049                smallPoolDepth);
1050        if (nfsGlob.smallPool == NULL) {
1051                goto cleanup;
1052        }
1053
1054        nfsGlob.bigPool = rpcUdpXactPoolCreate(
1055                NFS_PROGRAM,
1056                NFS_VERSION_2,
1057                CONFIG_NFS_BIG_XACT_SIZE,
1058                bigPoolDepth);
1059        if (nfsGlob.bigPool == NULL) {
1060                goto cleanup;
1061        }
1062
1063        if (sizeof(ino_t) < sizeof(u_int)) {
1064                fprintf(stderr,
1065                        "WARNING: Using 'short st_ino' hits performance and may fail to access/find correct files\n");
1066                fprintf(stderr,
1067                        "you should fix newlib's sys/stat.h - for now I'll enable a hack...\n");
1068
1069        }
1070
1071        return 0;
1072
1073cleanup:
1074
1075        nfsCleanup();
1076        initialised = 0;
1077
1078        return -1;
1079}
1080
1081/* Driver cleanup code
1082 */
1083int
1084nfsCleanup(void)
1085{
1086int                     refuse;
1087
1088        LOCK(nfsGlob.llock);
1089        if ( (refuse = nfsGlob.num_mounted_fs) ) {
1090                fprintf(stderr,"Refuse to unload NFS; %i filesystems still mounted.\n",
1091                                                refuse);
1092                nfsMountsShow(stderr);
1093                /* yes, printing is slow - but since you try to unload the driver,
1094                 * you assume nobody is using NFS, so what if they have to wait?
1095                 */
1096                UNLOCK(nfsGlob.llock);
1097                return -1;
1098        }
1099
1100        if (nfsGlob.smallPool != NULL) {
1101                rpcUdpXactPoolDestroy(nfsGlob.smallPool);
1102                nfsGlob.smallPool = NULL;
1103        }
1104
1105        if (nfsGlob.bigPool != NULL) {
1106                rpcUdpXactPoolDestroy(nfsGlob.bigPool);
1107                nfsGlob.bigPool = NULL;
1108        }
1109
1110        if (nfsGlob.nfs_major != 0xffffffff) {
1111                rtems_io_unregister_driver(nfsGlob.nfs_major);
1112                nfsGlob.nfs_major = 0xffffffff;
1113        }
1114
1115        UNLOCK(nfsGlob.llock);
1116
1117        rtems_recursive_mutex_destroy(&nfsGlob.lock);
1118        rtems_recursive_mutex_destroy(&nfsGlob.llock);
1119
1120        return 0;
1121}
1122
1123/* NFS RPC wrapper.
1124 *
1125 * ARGS:        srvr    the NFS server we want to call
1126 *                      proc    the NFSPROC_xx we want to invoke
1127 *                      xargs   xdr routine to wrap the arguments
1128 *                      pargs   pointer to the argument object
1129 *                      xres    xdr routine to unwrap the results
1130 *                      pres    pointer to the result object
1131 *
1132 * RETURNS:     0 on success, -1 on error with errno set.
1133 *
1134 * NOTE:        the caller assumes that errno is set to
1135 *                      a nonzero value if this routine returns
1136 *                      an error (nonzero return value).
1137 *
1138 *                      This routine prints RPC error messages to
1139 *                      stderr.
1140 */
1141STATIC int
1142nfscall(
1143        RpcUdpServer    srvr,
1144        int                             proc,
1145        xdrproc_t               xargs,
1146        void *                  pargs,
1147        xdrproc_t               xres,
1148        void *                  pres)
1149{
1150RpcUdpXact              xact;
1151enum clnt_stat  stat;
1152RpcUdpXactPool  pool;
1153int                             rval = -1;
1154
1155
1156        switch (proc) {
1157                case NFSPROC_SYMLINK:
1158                case NFSPROC_WRITE:
1159                                        pool = nfsGlob.bigPool;         break;
1160                default:        pool = nfsGlob.smallPool;       break;
1161        }
1162
1163        xact = rpcUdpXactPoolGet(pool, XactGetCreate);
1164
1165        if ( !xact ) {
1166                errno = ENOMEM;
1167                return -1;
1168        }
1169
1170        if ( RPC_SUCCESS != (stat=rpcUdpSend(
1171                                                                xact,
1172                                                                srvr,
1173                                                                NFSCALL_TIMEOUT,
1174                                                                proc,
1175                                                                xres,
1176                                                                pres,
1177                                                                xargs,
1178                                                                pargs,
1179                                                                0)) ||
1180             RPC_SUCCESS != (stat=rpcUdpRcv(xact)) ) {
1181
1182                fprintf(stderr,
1183                                "NFS (proc %i) - %s\n",
1184                                proc,
1185                                clnt_sperrno(stat));
1186
1187                switch (stat) {
1188                        /* TODO: this is probably not complete and/or fully accurate */
1189                        case RPC_CANTENCODEARGS : errno = EINVAL;       break;
1190                        case RPC_AUTHERROR      : errno = EPERM;        break;
1191
1192                        case RPC_CANTSEND               :
1193                        case RPC_CANTRECV               : /* hope they have errno set */
1194                        case RPC_SYSTEMERROR    : break;
1195
1196                        default                 : errno = EIO;          break;
1197                }
1198        } else {
1199                rval = 0;
1200        }
1201
1202        /* release the transaction back into the pool */
1203        rpcUdpXactPoolPut(xact);
1204
1205        if (rval && !errno)
1206                errno = EIO;
1207
1208        return rval;
1209}
1210
1211/* Check the 'age' of a node's stats
1212 * and read the attributes from the server
1213 * if necessary.
1214 *
1215 * ARGS:        node    node to update
1216 *                      force   enforce updating ignoring
1217 *                                      the timestamp/age
1218 *
1219 * RETURNS:     0 on success,
1220 *                      -1 on failure with errno set
1221 */
1222
1223static int
1224updateAttr(NfsNode node, int force)
1225{
1226        int rv = 0;
1227
1228        if (force
1229#ifdef CONFIG_ATTR_LIFETIME
1230                || (nowSeconds() - node->age > CONFIG_ATTR_LIFETIME)
1231#endif
1232        ) {
1233                rv = nfscall(
1234                        node->nfs->server,
1235                        NFSPROC_GETATTR,
1236                        (xdrproc_t) xdr_nfs_fh, &SERP_FILE(node),
1237                        (xdrproc_t) xdr_attrstat, &node->serporid
1238                );
1239
1240                if (rv == 0) {
1241                        rv = nfsEvaluateStatus(node->serporid.status);
1242
1243                        if (rv == 0) {
1244                                node->age = nowSeconds();
1245                        }
1246                }
1247        }
1248
1249        return rv;
1250}
1251
1252/*
1253 * IP address helper.
1254 *
1255 * initialize a sockaddr_in from a
1256 * [<uid>'.'<gid>'@']<host>':'<path>" string and let
1257 * pPath point to the <path> part; retrieve the optional
1258 * uid/gids
1259 *
1260 * ARGS:        see description above
1261 *
1262 * RETURNS:     0 on success,
1263 *                      -1 on failure with errno set
1264 */
1265static int
1266buildIpAddr(u_long *puid, u_long *pgid,
1267                        char **pHost, struct sockaddr_in *psa,
1268                        char **pPath)
1269{
1270struct hostent *h;
1271char    host[64];
1272char    *chpt = *pPath;
1273char    *path;
1274int             len;
1275
1276        if ( !chpt ) {
1277                errno = EINVAL;
1278                return -1;
1279        }
1280
1281        /* look for the optional uid/gid */
1282        if ( (chpt = strchr(chpt, UIDSEP)) ) {
1283                if ( 2 != sscanf(*pPath,"%li.%li",puid,pgid) ) {
1284                        errno = EINVAL;
1285                        return -1;
1286                }
1287                chpt++;
1288        } else {
1289                *puid = geteuid();
1290                *pgid = getegid();
1291                chpt  = *pPath;
1292        }
1293        if ( pHost )
1294                *pHost = chpt;
1295
1296        /* split the device name which is in the form
1297         *
1298         * <host> ':' <path>
1299         *
1300         * into its components using a local buffer
1301         */
1302
1303        if ( !(path = strchr(chpt, HOSTDELIM)) ||
1304              (len  = path - chpt) >= sizeof(host) - 1 ) {
1305                errno = EINVAL;
1306                return -1;
1307        }
1308        /* point to path beyond ':' */
1309        path++;
1310
1311        strncpy(host, chpt, len);
1312        host[len]=0;
1313
1314  /* BEGIN OF NON-THREAD SAFE REGION */
1315
1316        h = gethostbyname(host);
1317
1318        if ( !h ) {
1319                errno = EINVAL;
1320                return -1;
1321        }
1322
1323        memcpy(&psa->sin_addr, h->h_addr, sizeof (struct in_addr));
1324
1325  /* END OF NON-THREAD SAFE REGION */
1326
1327        psa->sin_family = AF_INET;
1328        psa->sin_port   = 0;
1329        *pPath          = path;
1330        return 0;
1331}
1332
1333/* wrapper similar to nfscall.
1334 * However, since it is not used
1335 * very often, the simpler and less
1336 * efficient rpcUdpCallRp API is used.
1337 *
1338 * ARGS:        see 'nfscall()' above
1339 *
1340 * RETURNS:     RPC status
1341 */
1342static enum clnt_stat
1343mntcall(
1344        struct sockaddr_in      *psrvr,
1345        int                                     proc,
1346        xdrproc_t                       xargs,
1347        void *                          pargs,
1348        xdrproc_t                       xres,
1349        void *                          pres,
1350        u_long                          uid,
1351        u_long                          gid)
1352{
1353#ifdef MOUNT_V1_PORT
1354int                                     retry;
1355#endif
1356enum clnt_stat          stat = RPC_FAILED;
1357
1358#ifdef MOUNT_V1_PORT
1359        /* if the portmapper fails, retry a fixed port */
1360        for (retry = 1, psrvr->sin_port = 0, stat = RPC_FAILED;
1361                 retry >= 0 && stat;
1362                 stat && (psrvr->sin_port = htons(MOUNT_V1_PORT)), retry-- )
1363#endif
1364                stat  = rpcUdpCallRp(
1365                                                psrvr,
1366                                                MOUNTPROG,
1367                                                MOUNTVERS,
1368                                                proc,
1369                                                xargs,
1370                                                pargs,
1371                                                xres,
1372                                                pres,
1373                                                uid,
1374                                                gid,
1375                                                MNTCALL_TIMEOUT
1376                                );
1377        return stat;
1378}
1379
1380/*****************************************
1381        RTEMS File System Operations for NFS
1382 *****************************************/
1383
1384static bool nfs_is_directory(
1385        rtems_filesystem_eval_path_context_t *ctx,
1386        void *arg
1387)
1388{
1389        bool is_dir = false;
1390        rtems_filesystem_location_info_t *currentloc =
1391                rtems_filesystem_eval_path_get_currentloc(ctx);
1392        NfsNode node = currentloc->node_access;
1393        int force_update = 0;
1394
1395        if (updateAttr(node, force_update) == 0) {
1396                is_dir = SERP_ATTR(node).type == NFDIR;
1397        }
1398
1399        return is_dir;
1400}
1401
1402static int nfs_search_in_directory(
1403        Nfs nfs,
1404        const NfsNode dir,
1405        char *part,
1406        NfsNode entry
1407)
1408{
1409        int rv;
1410
1411        entry->nfs = nfs;
1412
1413        /* lookup one element */
1414        SERP_ATTR(entry) = SERP_ATTR(dir);
1415        SERP_FILE(entry) = SERP_FILE(dir);
1416        SERP_ARGS(entry).diroparg.name = part;
1417
1418        /* remember args / directory fh */
1419        memcpy(&entry->args, &SERP_FILE(dir), sizeof(dir->args));
1420
1421#if DEBUG & DEBUG_EVALPATH
1422        fprintf(stderr,"Looking up '%s'\n",part);
1423#endif
1424
1425        rv = nfscall(
1426                nfs->server,
1427                NFSPROC_LOOKUP,
1428                (xdrproc_t) xdr_diropargs, &SERP_FILE(entry),
1429                (xdrproc_t) xdr_serporid,  &entry->serporid
1430        );
1431
1432        if (rv == 0 && entry->serporid.status == NFS_OK) {
1433                int force_update = 1;
1434
1435                rv = updateAttr(entry, force_update);
1436        } else {
1437                rv = -1;
1438        }
1439
1440        return rv;
1441}
1442
1443static void nfs_eval_follow_link(
1444        rtems_filesystem_eval_path_context_t *ctx,
1445        NfsNode link
1446)
1447{
1448        const size_t len = NFS_MAXPATHLEN + 1;
1449        char *buf = malloc(len);
1450
1451        if (buf != NULL) {
1452                ssize_t rv = nfs_readlink_with_node(link, buf, len);
1453
1454                if (rv >= 0) {
1455                        rtems_filesystem_eval_path_recursive(ctx, buf, (size_t) rv);
1456                } else {
1457                        rtems_filesystem_eval_path_error(ctx, 0);
1458                }
1459
1460                free(buf);
1461        } else {
1462                rtems_filesystem_eval_path_error(ctx, ENOMEM);
1463        }
1464}
1465
1466static void nfs_eval_set_handlers(
1467        rtems_filesystem_eval_path_context_t *ctx,
1468        ftype type
1469)
1470{
1471        rtems_filesystem_location_info_t *currentloc =
1472                rtems_filesystem_eval_path_get_currentloc(ctx);
1473
1474        switch (type) {
1475                case NFDIR:
1476                        currentloc->handlers = &nfs_dir_file_handlers;
1477                        break;
1478                case NFREG:
1479                        currentloc->handlers = &nfs_file_file_handlers;
1480                        break;
1481                case NFLNK:
1482                        currentloc->handlers = &nfs_link_file_handlers;
1483                        break;
1484                default:
1485                        currentloc->handlers = &rtems_filesystem_handlers_default;
1486                        break;
1487        }
1488}
1489
1490static int nfs_move_node(NfsNode dst, const NfsNode src, const char *part)
1491{
1492        int rv = 0;
1493
1494        if (dst->str != NULL) {
1495#if DEBUG & DEBUG_COUNT_NODES
1496                rtems_interrupt_lock_context lock_context;
1497                NFS_GLOBAL_ACQUIRE(&lock_context);
1498                        dst->nfs->stringsInUse--;
1499                NFS_GLOBAL_RELEASE(&lock_context);
1500#endif
1501                free(dst->str);
1502        }
1503
1504        *dst = *src;
1505
1506        dst->str = dst->args.name = strdup(part);
1507        if (dst->str != NULL) {
1508#if DEBUG & DEBUG_COUNT_NODES
1509                rtems_interrupt_lock_context lock_context;
1510                NFS_GLOBAL_ACQUIRE(&lock_context);
1511                        dst->nfs->stringsInUse++;
1512                NFS_GLOBAL_RELEASE(&lock_context);
1513#endif
1514        } else {
1515                rv = -1;
1516        }
1517
1518        return rv;
1519}
1520
1521static rtems_filesystem_eval_path_generic_status nfs_eval_part(
1522        rtems_filesystem_eval_path_context_t *ctx,
1523        char *part
1524)
1525{
1526        rtems_filesystem_eval_path_generic_status status =
1527                RTEMS_FILESYSTEM_EVAL_PATH_GENERIC_DONE;
1528        rtems_filesystem_location_info_t *currentloc =
1529                rtems_filesystem_eval_path_get_currentloc(ctx);
1530        Nfs nfs = currentloc->mt_entry->fs_info;
1531        NfsNode dir = currentloc->node_access;
1532        NfsNodeRec entry;
1533        int rv = nfs_search_in_directory(nfs, dir, part, &entry);
1534
1535        if (rv == 0) {
1536                bool terminal = !rtems_filesystem_eval_path_has_path(ctx);
1537                int eval_flags = rtems_filesystem_eval_path_get_flags(ctx);
1538                bool follow_sym_link = (eval_flags & RTEMS_FS_FOLLOW_SYM_LINK) != 0;
1539                ftype type = SERP_ATTR(&entry).type;
1540
1541                rtems_filesystem_eval_path_clear_token(ctx);
1542
1543                if (type == NFLNK && (follow_sym_link || !terminal)) {
1544                        nfs_eval_follow_link(ctx, &entry);
1545                } else {
1546                        rv = nfs_move_node(dir, &entry, part);
1547                        if (rv == 0) {
1548                                nfs_eval_set_handlers(ctx, type);
1549                                if (!terminal) {
1550                                        status = RTEMS_FILESYSTEM_EVAL_PATH_GENERIC_CONTINUE;
1551                                }
1552                        } else {
1553                                rtems_filesystem_eval_path_error(ctx, ENOMEM);
1554                        }
1555                }
1556        } else {
1557                status = RTEMS_FILESYSTEM_EVAL_PATH_GENERIC_NO_ENTRY;
1558        }
1559
1560        return status;
1561}
1562
1563static rtems_filesystem_eval_path_generic_status nfs_eval_token(
1564        rtems_filesystem_eval_path_context_t *ctx,
1565        void *arg,
1566        const char *token,
1567        size_t tokenlen
1568)
1569{
1570        rtems_filesystem_eval_path_generic_status status =
1571                RTEMS_FILESYSTEM_EVAL_PATH_GENERIC_DONE;
1572
1573        if (rtems_filesystem_is_current_directory(token, tokenlen)) {
1574                rtems_filesystem_eval_path_clear_token(ctx);
1575                if (rtems_filesystem_eval_path_has_path(ctx)) {
1576                        status = RTEMS_FILESYSTEM_EVAL_PATH_GENERIC_CONTINUE;
1577                }
1578        } else {
1579                char *part = nfs_dupname(token, tokenlen);
1580
1581                if (part != NULL) {
1582                        status = nfs_eval_part(ctx, part);
1583                        free(part);
1584                } else {
1585                        rtems_filesystem_eval_path_error(ctx, ENOMEM);
1586                }
1587        }
1588
1589        return status;
1590}
1591
1592static const rtems_filesystem_eval_path_generic_config nfs_eval_config = {
1593        .is_directory = nfs_is_directory,
1594        .eval_token = nfs_eval_token
1595};
1596
1597static void nfs_eval_path(rtems_filesystem_eval_path_context_t *ctx)
1598{
1599        rtems_filesystem_eval_path_generic(ctx, NULL, &nfs_eval_config);
1600}
1601
1602/* create a hard link */
1603
1604static int nfs_link(
1605        const rtems_filesystem_location_info_t *parentloc,
1606        const rtems_filesystem_location_info_t *targetloc,
1607        const char *name,
1608        size_t namelen
1609)
1610{
1611int rv = 0;
1612NfsNode pNode = parentloc->node_access;
1613nfsstat status;
1614NfsNode tNode = targetloc->node_access;
1615char *dupname;
1616
1617        dupname = nfs_dupname(name, namelen);
1618        if (dupname == NULL)
1619                return -1;
1620
1621#if DEBUG & DEBUG_SYSCALLS
1622        fprintf(stderr,"Creating link '%s'\n",dupname);
1623#endif
1624
1625        memcpy(&SERP_ARGS(tNode).linkarg.to.dir,
1626                   &SERP_FILE(pNode),
1627                   sizeof(SERP_FILE(pNode)));
1628
1629        SERP_ARGS(tNode).linkarg.to.name = dupname;
1630
1631        rv = nfscall(
1632                tNode->nfs->server,
1633                NFSPROC_LINK,
1634                (xdrproc_t)xdr_linkargs, &SERP_FILE(tNode),
1635                (xdrproc_t)xdr_nfsstat, &status
1636        );
1637
1638        if (rv == 0) {
1639                rv = nfsEvaluateStatus(status);
1640#if DEBUG & DEBUG_SYSCALLS
1641                if (rv != 0) {
1642                        perror("nfs_link");
1643                }
1644#endif
1645        }
1646
1647        free(dupname);
1648
1649        return rv;
1650
1651}
1652
1653static int nfs_do_unlink(
1654        const rtems_filesystem_location_info_t *parentloc,
1655        const rtems_filesystem_location_info_t *loc,
1656        int                                                               proc
1657)
1658{
1659int rv = 0;
1660nfsstat                 status;
1661NfsNode                 node  = loc->node_access;
1662Nfs                             nfs   = node->nfs;
1663#if DEBUG & DEBUG_SYSCALLS
1664char                    *name = NFSPROC_REMOVE == proc ?
1665                                                        "nfs_unlink" : "nfs_rmdir";
1666#endif
1667
1668        /* The FS generics have determined that pathloc is _not_
1669         * a directory. Hence we may assume that the parent
1670         * is in our NFS.
1671         */
1672
1673#if DEBUG & DEBUG_SYSCALLS
1674        assert( node->args.name == node->str && node->str );
1675
1676        fprintf(stderr,"%s '%s'\n", name, node->args.name);
1677#endif
1678
1679        rv = nfscall(
1680                nfs->server,
1681                proc,
1682                (xdrproc_t)xdr_diropargs, &node->args,
1683                (xdrproc_t)xdr_nfsstat, &status
1684        );
1685
1686        if (rv == 0) {
1687                rv = nfsEvaluateStatus(status);
1688#if DEBUG & DEBUG_SYSCALLS
1689                if (rv != 0) {
1690                        perror(name);
1691                }
1692#endif
1693        }
1694
1695        return rv;
1696}
1697
1698static int nfs_chown(
1699        const rtems_filesystem_location_info_t  *pathloc,       /* IN */
1700        uid_t                                    owner,         /* IN */
1701        gid_t                                    group          /* IN */
1702)
1703{
1704sattr   arg;
1705
1706        arg.uid = owner;
1707        arg.gid = group;
1708
1709        return nfs_sattr(pathloc->node_access, &arg, SATTR_UID | SATTR_GID);
1710
1711}
1712
1713static int nfs_clonenode(rtems_filesystem_location_info_t *loc)
1714{
1715        NfsNode node = loc->node_access;
1716
1717        LOCK(nfsGlob.lock);
1718        node = nfsNodeClone(node);
1719        UNLOCK(nfsGlob.lock);
1720
1721        loc->node_access = node;
1722
1723        return node != NULL ? 0 : -1;
1724}
1725
1726/* Cleanup the FS private info attached to pathloc->node_access */
1727static void nfs_freenode(
1728        const rtems_filesystem_location_info_t      *pathloc       /* IN */
1729)
1730{
1731#if DEBUG & DEBUG_COUNT_NODES
1732Nfs     nfs    = ((NfsNode)pathloc->node_access)->nfs;
1733
1734        /* print counts at entry where they are > 0 so 'nfs' is safe from being destroyed
1735         * and there's no race condition
1736         */
1737        fprintf(stderr,
1738                        "entering freenode, in use count is %i nodes, %i strings\n",
1739                        nfs->nodesInUse,
1740                        nfs->stringsInUse);
1741#endif
1742
1743        nfsNodeDestroy(pathloc->node_access);
1744}
1745
1746/* NOTE/TODO: mounting on top of NFS is not currently supported
1747 *
1748 * Challenge: stateless protocol. It would be possible to
1749 * delete mount points on the server. We would need some sort
1750 * of a 'garbage collector' looking for dead/unreachable
1751 * mount points and unmounting them.
1752 * Also, the path evaluation routine would have to check
1753 * for crossing mount points. Crossing over from one NFS
1754 * into another NFS could probably handled iteratively
1755 * rather than by recursion.
1756 */
1757
1758int rtems_nfs_initialize(
1759  rtems_filesystem_mount_table_entry_t *mt_entry,
1760  const void                           *data
1761)
1762{
1763char                            *host;
1764struct sockaddr_in      saddr;
1765enum clnt_stat          stat;
1766fhstatus                        fhstat;
1767u_long                          uid,gid;
1768#ifdef NFS_V2_PORT
1769int                                     retry;
1770#endif
1771Nfs                                     nfs       = 0;
1772NfsNode                         rootNode  = 0;
1773RpcUdpServer            nfsServer = 0;
1774int                                     e         = -1;
1775char                            *path     = mt_entry->dev;
1776
1777  if (rpcUdpInit () < 0) {
1778    fprintf (stderr, "error: initialising RPC\n");
1779    return -1;
1780  }
1781
1782        if (nfsInit(0, 0) != 0) {
1783                fprintf (stderr, "error: initialising NFS\n");
1784                return -1;
1785        };
1786
1787#if 0
1788        printf("Trying to mount %s on %s\n",path,mntpoint);
1789#endif
1790
1791        if ( buildIpAddr(&uid, &gid, &host, &saddr, &path) )
1792                return -1;
1793
1794#ifdef NFS_V2_PORT
1795        /* if the portmapper fails, retry a fixed port */
1796        for (retry = 1, saddr.sin_port = 0, stat = RPC_FAILED;
1797                 retry >= 0 && stat;
1798                 stat && (saddr.sin_port = htons(NFS_V2_PORT)), retry-- )
1799#endif
1800                stat = rpcUdpServerCreate(
1801                                        &saddr,
1802                                        NFS_PROGRAM,
1803                                        NFS_VERSION_2,
1804                                        uid,
1805                                        gid,
1806                                        &nfsServer
1807                                        );
1808
1809        if ( RPC_SUCCESS != stat ) {
1810                fprintf(stderr,
1811                                "Unable to contact NFS server - invalid port? (%s)\n",
1812                                clnt_sperrno(stat));
1813                e = EPROTONOSUPPORT;
1814                goto cleanup;
1815        }
1816
1817
1818        /* first, try to ping the NFS server by
1819         * calling the NULL proc.
1820         */
1821        if ( nfscall(nfsServer,
1822                                         NFSPROC_NULL,
1823                                         (xdrproc_t)xdr_void, 0,
1824                                         (xdrproc_t)xdr_void, 0) ) {
1825
1826                fputs("NFS Ping ",stderr);
1827                fwrite(host, 1, path-host-1, stderr);
1828                fprintf(stderr," failed: %s\n", strerror(errno));
1829
1830                e = errno ? errno : EIO;
1831                goto cleanup;
1832        }
1833
1834        /* that seemed to work - we now try the
1835         * actual mount
1836         */
1837
1838        /* reuse server address but let the mntcall()
1839         * search for the mountd's port
1840         */
1841        saddr.sin_port = 0;
1842
1843        stat = mntcall( &saddr,
1844                                        MOUNTPROC_MNT,
1845                                        (xdrproc_t)xdr_dirpath,
1846                                        &path,
1847                                        (xdrproc_t)xdr_fhstatus,
1848                                        &fhstat,
1849                                        uid,
1850                                        gid );
1851
1852        if (stat) {
1853                fprintf(stderr,"MOUNT -- %s\n",clnt_sperrno(stat));
1854                if ( e<=0 )
1855                        e = EIO;
1856                goto cleanup;
1857        } else if (NFS_OK != (e=fhstat.fhs_status)) {
1858                fprintf(stderr,"MOUNT: %s\n",strerror(e));
1859                goto cleanup;
1860        }
1861
1862        nfs = nfsCreate(nfsServer);
1863        assert( nfs );
1864        nfsServer = 0;
1865
1866        nfs->uid  = uid;
1867        nfs->gid  = gid;
1868
1869        /* that seemed to work - we now create the root node
1870         * and we also must obtain the root node attributes
1871         */
1872        rootNode = nfsNodeCreate(nfs, &fhstat.fhstatus_u.fhs_fhandle);
1873        assert( rootNode );
1874
1875        if ( updateAttr(rootNode, 1 /* force */) ) {
1876                e = errno;
1877                goto cleanup;
1878        }
1879
1880        /* looks good so far */
1881
1882        mt_entry->mt_fs_root->location.node_access = rootNode;
1883
1884        rootNode = 0;
1885
1886        mt_entry->ops = &nfs_fs_ops;
1887        mt_entry->mt_fs_root->location.handlers  = &nfs_dir_file_handlers;
1888        mt_entry->pathconf_limits_and_options = &nfs_limits_and_options;
1889
1890        LOCK(nfsGlob.llock);
1891                nfsGlob.num_mounted_fs++;
1892                /* allocate a new ID for this FS */
1893                nfs->id = nfsGlob.fs_ids++;
1894        UNLOCK(nfsGlob.llock);
1895
1896        mt_entry->fs_info                                = nfs;
1897        nfs->mt_entry                                    = mt_entry;
1898        nfs = 0;
1899
1900        e = 0;
1901
1902cleanup:
1903        if (nfs)
1904                nfsDestroy(nfs);
1905        if (nfsServer)
1906                rpcUdpServerDestroy(nfsServer);
1907        if (rootNode)
1908                nfsNodeDestroy(rootNode);
1909        if (e)
1910                rtems_set_errno_and_return_minus_one(e);
1911        else
1912                return 0;
1913}
1914
1915/* This op is called when they try to unmount THIS fs */
1916STATIC void nfs_fsunmount_me(
1917        rtems_filesystem_mount_table_entry_t *mt_entry    /* in */
1918)
1919{
1920enum clnt_stat          stat;
1921struct sockaddr_in      saddr;
1922char                    *path = mt_entry->dev;
1923int                     nodesInUse;
1924u_long                  uid,gid;
1925int                     status;
1926
1927LOCK(nfsGlob.llock);
1928        nodesInUse = ((Nfs)mt_entry->fs_info)->nodesInUse;
1929
1930        if (nodesInUse > 1 /* one ref to the root node used by us */) {
1931                UNLOCK(nfsGlob.llock);
1932                fprintf(stderr,
1933                                "Refuse to unmount; there are still %i nodes in use (1 used by us)\n",
1934                                nodesInUse);
1935                rtems_fatal_error_occurred(0xdeadbeef);
1936                return;
1937        }
1938
1939        status = buildIpAddr(&uid, &gid, 0, &saddr, &path);
1940        assert( !status );
1941
1942        stat = mntcall( &saddr,
1943                                        MOUNTPROC_UMNT,
1944                                        (xdrproc_t)xdr_dirpath, &path,
1945                                        (xdrproc_t)xdr_void,     0,
1946                                    uid,
1947                                    gid
1948                                  );
1949
1950        if (stat) {
1951                UNLOCK(nfsGlob.llock);
1952                fprintf(stderr,"NFS UMOUNT -- %s\n", clnt_sperrno(stat));
1953                return;
1954        }
1955
1956        nfsNodeDestroy(mt_entry->mt_fs_root->location.node_access);
1957        mt_entry->mt_fs_root->location.node_access = 0;
1958
1959        nfsDestroy(mt_entry->fs_info);
1960        mt_entry->fs_info = 0;
1961
1962        nfsGlob.num_mounted_fs--;
1963UNLOCK(nfsGlob.llock);
1964}
1965
1966static int nfs_mknod(
1967        const rtems_filesystem_location_info_t *parentloc,
1968        const char *name,
1969        size_t namelen,
1970        mode_t mode,
1971        dev_t dev
1972)
1973{
1974
1975int                                     rv = 0;
1976struct timeval                          now;
1977diropres                                res;
1978NfsNode                                 node = parentloc->node_access;
1979Nfs                                     nfs  = node->nfs;
1980mode_t                                  type = S_IFMT & mode;
1981char                                    *dupname;
1982
1983        if (type != S_IFDIR && type != S_IFREG)
1984                rtems_set_errno_and_return_minus_one(ENOTSUP);
1985
1986        dupname = nfs_dupname(name, namelen);
1987        if (dupname == NULL)
1988                return -1;
1989
1990#if DEBUG & DEBUG_SYSCALLS
1991        fprintf(stderr,"nfs_mknod: creating %s\n", dupname);
1992#endif
1993
1994        rtems_clock_get_tod_timeval(&now);
1995
1996        SERP_ARGS(node).createarg.name                  = dupname;
1997        SERP_ARGS(node).createarg.attributes.mode       = mode;
1998        SERP_ARGS(node).createarg.attributes.uid        = nfs->uid;
1999        SERP_ARGS(node).createarg.attributes.gid        = nfs->gid;
2000        SERP_ARGS(node).createarg.attributes.size       = 0;
2001        SERP_ARGS(node).createarg.attributes.atime.seconds      = now.tv_sec;
2002        SERP_ARGS(node).createarg.attributes.atime.useconds     = now.tv_usec;
2003        SERP_ARGS(node).createarg.attributes.mtime.seconds      = now.tv_sec;
2004        SERP_ARGS(node).createarg.attributes.mtime.useconds     = now.tv_usec;
2005
2006        rv = nfscall(
2007                nfs->server,
2008                (type == S_IFDIR) ? NFSPROC_MKDIR : NFSPROC_CREATE,
2009                (xdrproc_t)xdr_createargs, &SERP_FILE(node),
2010                (xdrproc_t)xdr_diropres, &res
2011        );
2012
2013        if (rv == 0) {
2014                rv = nfsEvaluateStatus(res.status);
2015#if DEBUG & DEBUG_SYSCALLS
2016                if (rv != 0) {
2017                        perror("nfs_mknod");
2018                }
2019#endif
2020        }
2021
2022        free(dupname);
2023
2024        return rv;
2025}
2026
2027static int nfs_rmnod(
2028        const rtems_filesystem_location_info_t *parentloc,
2029        const rtems_filesystem_location_info_t *loc
2030)
2031{
2032        int rv = 0;
2033        NfsNode node  = loc->node_access;
2034        int force_update = 0;
2035
2036        if (updateAttr(node, force_update) == 0) {
2037                int proc = SERP_ATTR(node).type == NFDIR
2038                        ? NFSPROC_RMDIR
2039                                : NFSPROC_REMOVE;
2040
2041                rv = nfs_do_unlink(parentloc, loc, proc);
2042        } else {
2043                rv = -1;
2044        }
2045
2046        return rv;
2047}
2048
2049static int nfs_utime(
2050        const rtems_filesystem_location_info_t  *pathloc, /* IN */
2051        time_t                                   actime,  /* IN */
2052        time_t                                   modtime  /* IN */
2053)
2054{
2055sattr   arg;
2056
2057        /* TODO: add rtems EPOCH - UNIX EPOCH seconds */
2058        arg.atime.seconds  = actime;
2059        arg.atime.useconds = 0;
2060        arg.mtime.seconds  = modtime;
2061        arg.mtime.useconds = 0;
2062
2063        return nfs_sattr(pathloc->node_access, &arg, SATTR_ATIME | SATTR_MTIME);
2064}
2065
2066static int nfs_symlink(
2067        const rtems_filesystem_location_info_t *parentloc,
2068        const char *name,
2069        size_t namelen,
2070        const char *target
2071)
2072{
2073int                                     rv = 0;
2074struct timeval                          now;
2075nfsstat                                 status;
2076NfsNode                                 node = parentloc->node_access;
2077Nfs                                     nfs  = node->nfs;
2078char                                    *dupname;
2079
2080        dupname = nfs_dupname(name, namelen);
2081        if (dupname == NULL)
2082                return -1;
2083
2084#if DEBUG & DEBUG_SYSCALLS
2085        fprintf(stderr,"nfs_symlink: creating %s -> %s\n", dupname, target);
2086#endif
2087
2088        rtems_clock_get_tod_timeval(&now);
2089
2090        SERP_ARGS(node).symlinkarg.name                 = dupname;
2091        SERP_ARGS(node).symlinkarg.to                           = (nfspath) target;
2092
2093        SERP_ARGS(node).symlinkarg.attributes.mode      = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO;
2094        SERP_ARGS(node).symlinkarg.attributes.uid       = nfs->uid;
2095        SERP_ARGS(node).symlinkarg.attributes.gid       = nfs->gid;
2096        SERP_ARGS(node).symlinkarg.attributes.size      = 0;
2097        SERP_ARGS(node).symlinkarg.attributes.atime.seconds  = now.tv_sec;
2098        SERP_ARGS(node).symlinkarg.attributes.atime.useconds = now.tv_usec;
2099        SERP_ARGS(node).symlinkarg.attributes.mtime.seconds  = now.tv_sec;
2100        SERP_ARGS(node).symlinkarg.attributes.mtime.useconds = now.tv_usec;
2101
2102        rv = nfscall(
2103                nfs->server,
2104                NFSPROC_SYMLINK,
2105                (xdrproc_t)xdr_symlinkargs, &SERP_FILE(node),
2106                (xdrproc_t)xdr_nfsstat, &status
2107        );
2108
2109        if (rv == 0) {
2110                rv = nfsEvaluateStatus(status);
2111#if DEBUG & DEBUG_SYSCALLS
2112                perror("nfs_symlink");
2113#endif
2114        }
2115
2116        free(dupname);
2117
2118        return rv;
2119}
2120
2121static ssize_t nfs_readlink_with_node(
2122        NfsNode node,
2123        char *buf,
2124        size_t len
2125)
2126{
2127        ssize_t rv;
2128        Nfs nfs = node->nfs;
2129        readlinkres_strbuf rr;
2130
2131        rr.strbuf.buf = buf;
2132        rr.strbuf.max = len - 1;
2133
2134        rv = nfscall(
2135                nfs->server,
2136                NFSPROC_READLINK,
2137                (xdrproc_t)xdr_nfs_fh, &SERP_FILE(node),
2138                (xdrproc_t)xdr_readlinkres_strbuf, &rr
2139        );
2140
2141        if (rv == 0) {
2142                rv = nfsEvaluateStatus(rr.status);
2143
2144                if (rv == 0) {
2145                        rv = (ssize_t) strlen(rr.strbuf.buf);
2146                } else {
2147#if DEBUG & DEBUG_SYSCALLS
2148                        perror("nfs_readlink_with_node");
2149#endif
2150                }
2151        }
2152
2153        return rv;
2154}
2155
2156static ssize_t nfs_readlink(
2157        const rtems_filesystem_location_info_t *loc,
2158        char *buf,
2159        size_t len
2160)
2161{
2162        NfsNode node = loc->node_access;
2163
2164        return nfs_readlink_with_node(node, buf, len);
2165}
2166
2167static int nfs_rename(
2168        const rtems_filesystem_location_info_t *oldparentloc,
2169        const rtems_filesystem_location_info_t *oldloc,
2170        const rtems_filesystem_location_info_t *newparentloc,
2171        const char *name,
2172        size_t namelen
2173)
2174{
2175        int rv = 0;
2176        char *dupname = nfs_dupname(name, namelen);
2177
2178        if (dupname != NULL) {
2179                NfsNode oldParentNode = oldparentloc->node_access;
2180                NfsNode oldNode = oldloc->node_access;
2181                NfsNode newParentNode = newparentloc->node_access;
2182                Nfs nfs = oldParentNode->nfs;
2183                const nfs_fh *toDirSrc = &SERP_FILE(newParentNode);
2184                nfs_fh *toDirDst = &SERP_ARGS(oldParentNode).renamearg.to.dir;
2185                nfsstat status;
2186
2187                SERP_ARGS(oldParentNode).renamearg.name = oldNode->str;
2188                SERP_ARGS(oldParentNode).renamearg.to.name = dupname;
2189                memcpy(toDirDst, toDirSrc, sizeof(*toDirDst));
2190
2191                rv = nfscall(
2192                        nfs->server,
2193                        NFSPROC_RENAME,
2194                        (xdrproc_t) xdr_renameargs,
2195                        &SERP_FILE(oldParentNode),
2196                        (xdrproc_t) xdr_nfsstat,
2197                        &status
2198                );
2199
2200                if (rv == 0) {
2201                        rv = nfsEvaluateStatus(status);
2202                }
2203
2204                free(dupname);
2205        } else {
2206                rv = -1;
2207        }
2208
2209        return rv;
2210}
2211
2212static void nfs_lock(const rtems_filesystem_mount_table_entry_t *mt_entry)
2213{
2214}
2215
2216static void nfs_unlock(const rtems_filesystem_mount_table_entry_t *mt_entry)
2217{
2218}
2219
2220static bool nfs_are_nodes_equal(
2221        const rtems_filesystem_location_info_t *a,
2222        const rtems_filesystem_location_info_t *b
2223)
2224{
2225        bool equal = false;
2226        NfsNode na = a->node_access;
2227
2228        if (updateAttr(na, 0) == 0) {
2229                NfsNode nb = b->node_access;
2230
2231                if (updateAttr(nb, 0) == 0) {
2232                        equal = SERP_ATTR(na).fileid == SERP_ATTR(nb).fileid
2233                                && SERP_ATTR(na).fsid == SERP_ATTR(nb).fsid;
2234                }
2235        }
2236
2237        return equal;
2238}
2239
2240static int nfs_fchmod(
2241        const rtems_filesystem_location_info_t *loc,
2242        mode_t mode
2243)
2244{
2245sattr   arg;
2246
2247        arg.mode = mode;
2248        return nfs_sattr(loc->node_access, &arg, SATTR_MODE);
2249
2250}
2251
2252const struct _rtems_filesystem_operations_table nfs_fs_ops = {
2253        .lock_h         = nfs_lock,
2254        .unlock_h       = nfs_unlock,
2255        .eval_path_h    = nfs_eval_path,
2256        .link_h         = nfs_link,
2257        .are_nodes_equal_h = nfs_are_nodes_equal,
2258        .mknod_h        = nfs_mknod,
2259        .rmnod_h        = nfs_rmnod,
2260        .fchmod_h       = nfs_fchmod,
2261        .chown_h        = nfs_chown,
2262        .clonenod_h     = nfs_clonenode,
2263        .freenod_h      = nfs_freenode,
2264        .mount_h        = rtems_filesystem_default_mount,
2265        .unmount_h      = rtems_filesystem_default_unmount,
2266        .fsunmount_me_h = nfs_fsunmount_me,
2267        .utime_h        = nfs_utime,
2268        .symlink_h      = nfs_symlink,
2269        .readlink_h     = nfs_readlink,
2270        .rename_h       = nfs_rename,
2271        .statvfs_h      = rtems_filesystem_default_statvfs
2272};
2273
2274/*****************************************
2275        File Handlers
2276
2277        NOTE: the FS generics expect a FS'
2278              evalpath_h() to switch the
2279                  pathloc->handlers according
2280                  to the pathloc/node's file
2281                  type.
2282                  We currently have 'file' and
2283                  'directory' handlers and very
2284                  few 'symlink' handlers.
2285
2286                  The handlers for each type are
2287                  implemented or #defined ZERO
2288                  in a 'nfs_file_xxx',
2289                  'nfs_dir_xxx', 'nfs_link_xxx'
2290                  sequence below this point.
2291
2292                  In some cases, a common handler,
2293                  can be used for all file types.
2294                  It is then simply called
2295                  'nfs_xxx'.
2296 *****************************************/
2297
2298/* stateless NFS protocol makes this trivial */
2299static int nfs_file_open(
2300        rtems_libio_t *iop,
2301        const char    *pathname,
2302        int           oflag,
2303        mode_t        mode
2304)
2305{
2306        return 0;
2307}
2308
2309/* reading directories is not stateless; we must
2310 * remember the last 'read' position, i.e.
2311 * the server 'cookie'. We do manage this information
2312 * attached to the pathinfo.node_access_2.
2313 */
2314static int nfs_dir_open(
2315        rtems_libio_t *iop,
2316        const char    *pathname,
2317        int           oflag,
2318        mode_t        mode
2319)
2320{
2321NfsNode         node = iop->pathinfo.node_access;
2322DirInfo         di;
2323
2324        /* create a readdirargs object and copy the file handle;
2325         * attach to the pathinfo.node_access_2
2326         */
2327
2328        di = (DirInfo) malloc(sizeof(*di));
2329        iop->pathinfo.node_access_2 = di;
2330
2331        if ( !di  ) {
2332                errno = ENOMEM;
2333                return -1;
2334        }
2335
2336        memcpy( &di->readdirargs.dir,
2337                        &SERP_FILE(node),
2338                        sizeof(di->readdirargs.dir) );
2339
2340        /* rewind cookie */
2341        memset( &di->readdirargs.cookie,
2342                0,
2343                sizeof(di->readdirargs.cookie) );
2344
2345        di->eofreached = FALSE;
2346
2347        return 0;
2348}
2349
2350static int nfs_file_close(
2351        rtems_libio_t *iop
2352)
2353{
2354        return 0;
2355}
2356
2357static int nfs_dir_close(
2358        rtems_libio_t *iop
2359)
2360{
2361        free(iop->pathinfo.node_access_2);
2362        iop->pathinfo.node_access_2 = 0;
2363        return 0;
2364}
2365
2366static ssize_t nfs_file_read_chunk(
2367        NfsNode node,
2368        uint32_t offset,
2369        void *buffer,
2370        size_t count
2371)
2372{
2373ssize_t rv;
2374readres rr;
2375Nfs             nfs  = node->nfs;
2376
2377        SERP_ARGS(node).readarg.offset          = offset;
2378        SERP_ARGS(node).readarg.count           = count;
2379        SERP_ARGS(node).readarg.totalcount      = UINT32_C(0xdeadbeef);
2380
2381        rr.readres_u.reply.data.data_val        = buffer;
2382
2383        rv = nfscall(
2384                nfs->server,
2385                NFSPROC_READ,
2386                (xdrproc_t)xdr_readargs, &SERP_FILE(node),
2387                (xdrproc_t)xdr_readres, &rr
2388        );
2389
2390        if (rv == 0) {
2391                rv = nfsEvaluateStatus(rr.status);
2392
2393                if (rv == 0) {
2394                        rv = rr.readres_u.reply.data.data_len;
2395
2396#if DEBUG & DEBUG_SYSCALLS
2397                        fprintf(stderr,
2398                                "Read %i (asked for %i) bytes from offset %i to 0x%08x\n",
2399                                rr.readres_u.reply.data.data_len,
2400                                count,
2401                                iop->offset,
2402                                rr.readres_u.reply.data.data_val);
2403#endif
2404                }
2405        }
2406
2407        return rv;
2408}
2409
2410static ssize_t nfs_file_read(
2411        rtems_libio_t *iop,
2412        void *buffer,
2413        size_t count
2414)
2415{
2416        ssize_t rv = 0;
2417        NfsNode node = iop->pathinfo.node_access;
2418        uint32_t offset = iop->offset;
2419        char *in = buffer;
2420
2421        if (iop->offset < 0) {
2422                errno = EINVAL;
2423                return -1;
2424        }
2425
2426        if ((uintmax_t) iop->offset >= UINT32_MAX) {
2427                errno = EFBIG;
2428                return -1;
2429        }
2430
2431        if (count > UINT32_MAX - offset) {
2432                count = UINT32_MAX - offset;
2433        }
2434
2435        do {
2436                size_t chunk = count <= NFS_MAXDATA ? count : NFS_MAXDATA;
2437                ssize_t done = nfs_file_read_chunk(node, offset, in, chunk);
2438
2439                if (done > 0) {
2440                        offset += (uint32_t) done;
2441                        in += done;
2442                        count -= (size_t) done;
2443                        rv += done;
2444                } else {
2445                        count = 0;
2446                        if (done < 0) {
2447                                rv = -1;
2448                        }
2449                }
2450        } while (count > 0);
2451
2452        if (rv > 0) {
2453                iop->offset = offset;
2454        }
2455
2456        return rv;
2457}
2458
2459/* this is called by readdir() / getdents() */
2460static ssize_t nfs_dir_read(
2461        rtems_libio_t *iop,
2462        void          *buffer,
2463        size_t        count
2464)
2465{
2466ssize_t rv;
2467DirInfo                 di     = iop->pathinfo.node_access_2;
2468RpcUdpServer    server = ((Nfs)iop->pathinfo.mt_entry->fs_info)->server;
2469
2470        if ( di->eofreached )
2471                return 0;
2472
2473        di->ptr = di->buf = buffer;
2474
2475        /* align + round down the buffer */
2476        count &= ~ (DIRENT_HEADER_SIZE - 1);
2477        di->len = count;
2478
2479#if 0
2480        /* now estimate the number of entries we should ask for */
2481        count /= DIRENT_HEADER_SIZE + CONFIG_AVG_NAMLEN;
2482
2483        /* estimate the encoded size that might take up */
2484        count *= dirres_entry_size + CONFIG_AVG_NAMLEN;
2485#else
2486        /* integer arithmetics are better done the other way round */
2487        count *= dirres_entry_size + CONFIG_AVG_NAMLEN;
2488        count /= DIRENT_HEADER_SIZE + CONFIG_AVG_NAMLEN;
2489#endif
2490
2491        if (count > NFS_MAXDATA)
2492                count = NFS_MAXDATA;
2493
2494        di->readdirargs.count = count;
2495
2496#if DEBUG & DEBUG_READDIR
2497        fprintf(stderr,
2498                        "Readdir: asking for %i XDR bytes, buffer is %i\n",
2499                        count, di->len);
2500#endif
2501
2502        rv = nfscall(
2503                server,
2504                NFSPROC_READDIR,
2505                (xdrproc_t)xdr_readdirargs, &di->readdirargs,
2506                (xdrproc_t)xdr_dir_info, di
2507        );
2508
2509        if (rv == 0) {
2510                rv = nfsEvaluateStatus(di->status);
2511
2512                if (rv == 0) {
2513                        rv = (char*)di->ptr - (char*)buffer;
2514                }
2515        }
2516
2517        return rv;
2518}
2519
2520static ssize_t nfs_file_write(
2521        rtems_libio_t *iop,
2522        const void    *buffer,
2523        size_t        count
2524)
2525{
2526ssize_t rv;
2527NfsNode         node = iop->pathinfo.node_access;
2528Nfs                     nfs  = node->nfs;
2529
2530        if (count > NFS_MAXDATA)
2531                count = NFS_MAXDATA;
2532
2533
2534        SERP_ARGS(node).writearg.beginoffset = UINT32_C(0xdeadbeef);
2535        if (rtems_libio_iop_is_append(iop)) {
2536                if ( updateAttr(node, 0) ) {
2537                        return -1;
2538                }
2539                if (SERP_ATTR(node).size >= UINT32_MAX) {
2540                        errno = EFBIG;
2541                        return -1;
2542                }
2543                SERP_ARGS(node).writearg.offset = SERP_ATTR(node).size;
2544        } else {
2545                if (iop->offset < 0) {
2546                        errno = EINVAL;
2547                        return -1;
2548                }
2549                if ((uintmax_t) iop->offset >= UINT32_MAX) {
2550                        errno = EFBIG;
2551                        return -1;
2552                }
2553                SERP_ARGS(node).writearg.offset = iop->offset;
2554        }
2555
2556        if (count > UINT32_MAX - SERP_ARGS(node).writearg.offset) {
2557                count = UINT32_MAX - SERP_ARGS(node).writearg.offset;
2558        }
2559
2560        SERP_ARGS(node).writearg.totalcount        = UINT32_C(0xdeadbeef);
2561        SERP_ARGS(node).writearg.data.data_len = count;
2562        SERP_ARGS(node).writearg.data.data_val = (void*)buffer;
2563
2564        /* write XDR buffer size will be chosen by nfscall based
2565         * on the PROC specifier
2566         */
2567
2568        rv = nfscall(
2569                nfs->server,
2570                NFSPROC_WRITE,
2571                (xdrproc_t)xdr_writeargs, &SERP_FILE(node),
2572                (xdrproc_t)xdr_attrstat, &node->serporid
2573        );
2574
2575        if (rv == 0) {
2576                rv = nfsEvaluateStatus(node->serporid.status);
2577
2578                if (rv == 0) {
2579                        node->age = nowSeconds();
2580
2581                        iop->offset += count;
2582                        rv = count;
2583                } else {
2584                        /* try at least to recover the current attributes */
2585                        updateAttr(node, 1 /* force */);
2586                }
2587        }
2588
2589        return rv;
2590}
2591
2592static off_t nfs_dir_lseek(
2593        rtems_libio_t *iop,
2594        off_t          length,
2595        int            whence
2596)
2597{
2598        off_t rv = rtems_filesystem_default_lseek_directory(iop, length, whence);
2599
2600        if (rv == 0) {
2601                DirInfo di = iop->pathinfo.node_access_2;
2602                nfscookie *cookie = &di->readdirargs.cookie;
2603
2604                di->eofreached = FALSE;
2605
2606                /* rewind cookie */
2607                memset(cookie, 0, sizeof(*cookie));
2608        }
2609
2610        return rv;
2611}
2612
2613#if 0   /* structure types for reference */
2614struct fattr {
2615                ftype type;
2616                u_int mode;
2617                u_int nlink;
2618                u_int uid;
2619                u_int gid;
2620                u_int size;
2621                u_int blocksize;
2622                u_int rdev;
2623                u_int blocks;
2624                u_int fsid;
2625                u_int fileid;
2626                nfstime atime;
2627                nfstime mtime;
2628                nfstime ctime;
2629};
2630
2631struct  stat
2632{
2633                dev_t         st_dev;
2634                ino_t         st_ino;
2635                mode_t        st_mode;
2636                nlink_t       st_nlink;
2637                uid_t         st_uid;
2638                gid_t         st_gid;
2639                dev_t         st_rdev;
2640                off_t         st_size;
2641                /* SysV/sco doesn't have the rest... But Solaris, eabi does.  */
2642#if defined(__svr4__) && !defined(__PPC__) && !defined(__sun__)
2643                time_t        st_atime;
2644                time_t        st_mtime;
2645                time_t        st_ctime;
2646#else
2647                time_t        st_atime;
2648                long          st_spare1;
2649                time_t        st_mtime;
2650                long          st_spare2;
2651                time_t        st_ctime;
2652                long          st_spare3;
2653                long          st_blksize;
2654                long          st_blocks;
2655                long      st_spare4[2];
2656#endif
2657};
2658#endif
2659
2660/* common for file/dir/link */
2661static int nfs_fstat(
2662        const rtems_filesystem_location_info_t *loc,
2663        struct stat *buf
2664)
2665{
2666NfsNode node = loc->node_access;
2667fattr   *fa  = &SERP_ATTR(node);
2668
2669        if (updateAttr(node, 0 /* only if old */)) {
2670                return -1;
2671        }
2672
2673/* done by caller
2674        memset(buf, 0, sizeof(*buf));
2675 */
2676
2677        /* translate */
2678
2679        /* one of the branches hopefully is optimized away */
2680        if (sizeof(ino_t) < sizeof(u_int)) {
2681        buf->st_dev             = NFS_MAKE_DEV_T_INO_HACK((NfsNode)loc->node_access);
2682        } else {
2683        buf->st_dev             = NFS_MAKE_DEV_T((NfsNode)loc->node_access);
2684        }
2685        buf->st_mode    = fa->mode;
2686        buf->st_nlink   = fa->nlink;
2687        buf->st_uid             = fa->uid;
2688        buf->st_gid             = fa->gid;
2689        buf->st_size    = fa->size;
2690        /* Set to "preferred size" of this NFS client implementation */
2691        buf->st_blksize = nfsStBlksize ? nfsStBlksize : fa->blocksize;
2692        buf->st_rdev    = fa->rdev;
2693        buf->st_blocks  = fa->blocks;
2694        buf->st_ino     = fa->fileid;
2695        buf->st_atime   = fa->atime.seconds;
2696        buf->st_mtime   = fa->mtime.seconds;
2697        buf->st_ctime   = fa->ctime.seconds;
2698
2699#if 0 /* NFS should return the modes */
2700        switch(fa->type) {
2701                default:
2702                case NFNON:
2703                case NFBAD:
2704                                break;
2705
2706                case NFSOCK: buf->st_mode |= S_IFSOCK; break;
2707                case NFFIFO: buf->st_mode |= S_IFIFO;  break;
2708                case NFREG : buf->st_mode |= S_IFREG;  break;
2709                case NFDIR : buf->st_mode |= S_IFDIR;  break;
2710                case NFBLK : buf->st_mode |= S_IFBLK;  break;
2711                case NFCHR : buf->st_mode |= S_IFCHR;  break;
2712                case NFLNK : buf->st_mode |= S_IFLNK;  break;
2713        }
2714#endif
2715
2716        return 0;
2717}
2718
2719/* a helper which does the real work for
2720 * a couple of handlers (such as chmod,
2721 * ftruncate or utime)
2722 */
2723static int
2724nfs_sattr(NfsNode node, sattr *arg, u_long mask)
2725{
2726int rv;
2727struct timeval                          now;
2728nfstime                                 nfsnow, t;
2729u_int                                   mode;
2730
2731        if (updateAttr(node, 0 /* only if old */))
2732                return -1;
2733
2734        rtems_clock_get_tod_timeval(&now);
2735
2736        /* TODO: add rtems EPOCH - UNIX EPOCH seconds */
2737        nfsnow.seconds  = now.tv_sec;
2738        nfsnow.useconds = now.tv_usec;
2739
2740        /* merge permission bits into existing type bits */
2741        mode = SERP_ATTR(node).mode;
2742        if (mask & SATTR_MODE) {
2743                mode &= S_IFMT;
2744                mode |= arg->mode & ~S_IFMT;
2745        } else {
2746                mode = -1;
2747        }
2748        SERP_ARGS(node).sattrarg.attributes.mode  = mode;
2749
2750        SERP_ARGS(node).sattrarg.attributes.uid   =
2751                (mask & SATTR_UID)  ? arg->uid : -1;
2752
2753        SERP_ARGS(node).sattrarg.attributes.gid   =
2754                (mask & SATTR_GID)  ? arg->gid : -1;
2755
2756        SERP_ARGS(node).sattrarg.attributes.size  =
2757                (mask & SATTR_SIZE) ? arg->size : -1;
2758
2759        if (mask & SATTR_ATIME)
2760                t = arg->atime;
2761        else if (mask & SATTR_TOUCHA)
2762                t = nfsnow;
2763        else
2764                t.seconds = t.useconds = -1;
2765        SERP_ARGS(node).sattrarg.attributes.atime = t;
2766
2767        if (mask & SATTR_ATIME)
2768                t = arg->mtime;
2769        else if (mask & SATTR_TOUCHA)
2770                t = nfsnow;
2771        else
2772                t.seconds = t.useconds = -1;
2773        SERP_ARGS(node).sattrarg.attributes.mtime = t;
2774
2775        node->serporid.status = NFS_OK;
2776
2777        rv = nfscall(
2778                node->nfs->server,
2779                NFSPROC_SETATTR,
2780                (xdrproc_t)xdr_sattrargs, &SERP_FILE(node),
2781                (xdrproc_t)xdr_attrstat, &node->serporid
2782        );
2783
2784        if (rv == 0) {
2785                rv = nfsEvaluateStatus(node->serporid.status);
2786
2787                if (rv == 0) {
2788                        node->age = nowSeconds();
2789                } else {
2790#if DEBUG & DEBUG_SYSCALLS
2791                        fprintf(stderr,"nfs_sattr: %s\n",strerror(errno));
2792#endif
2793                        /* try at least to recover the current attributes */
2794                        updateAttr(node, 1 /* force */);
2795                }
2796        } else {
2797#if DEBUG & DEBUG_SYSCALLS
2798                fprintf(stderr,
2799                                "nfs_sattr (mask 0x%08x): %s",
2800                                mask,
2801                                strerror(errno));
2802#endif
2803        }
2804
2805        return rv;
2806}
2807
2808/* just set the size attribute to 'length'
2809 * the server will take care of the rest :-)
2810 */
2811static int nfs_file_ftruncate(
2812        rtems_libio_t *iop,
2813        off_t          length
2814)
2815{
2816sattr                                   arg;
2817
2818        if (length < 0) {
2819                errno = EINVAL;
2820                return -1;
2821        }
2822
2823        if ((uintmax_t) length > UINT32_MAX) {
2824                errno = EFBIG;
2825                return -1;
2826        }
2827
2828        arg.size = length;
2829        /* must not modify any other attribute; if we are not the owner
2830         * of the file or directory but only have write access changing
2831         * any attribute besides 'size' will fail...
2832         */
2833        return nfs_sattr(iop->pathinfo.node_access,
2834                                         &arg,
2835                                         SATTR_SIZE);
2836}
2837
2838/* the file handlers table */
2839static const
2840struct _rtems_filesystem_file_handlers_r nfs_file_file_handlers = {
2841        .open_h      = nfs_file_open,
2842        .close_h     = nfs_file_close,
2843        .read_h      = nfs_file_read,
2844        .write_h     = nfs_file_write,
2845        .ioctl_h     = rtems_filesystem_default_ioctl,
2846        .lseek_h     = rtems_filesystem_default_lseek_file,
2847        .fstat_h     = nfs_fstat,
2848        .ftruncate_h = nfs_file_ftruncate,
2849        .fsync_h     = rtems_filesystem_default_fsync_or_fdatasync,
2850        .fdatasync_h = rtems_filesystem_default_fsync_or_fdatasync,
2851        .fcntl_h     = rtems_filesystem_default_fcntl,
2852        .kqfilter_h  = rtems_filesystem_default_kqfilter,
2853        .mmap_h      = rtems_filesystem_default_mmap,
2854        .poll_h      = rtems_filesystem_default_poll,
2855        .readv_h     = rtems_filesystem_default_readv,
2856        .writev_h    = rtems_filesystem_default_writev
2857};
2858
2859/* the directory handlers table */
2860static const
2861struct _rtems_filesystem_file_handlers_r nfs_dir_file_handlers = {
2862        .open_h      = nfs_dir_open,
2863        .close_h     = nfs_dir_close,
2864        .read_h      = nfs_dir_read,
2865        .write_h     = rtems_filesystem_default_write,
2866        .ioctl_h     = rtems_filesystem_default_ioctl,
2867        .lseek_h     = nfs_dir_lseek,
2868        .fstat_h     = nfs_fstat,
2869        .ftruncate_h = rtems_filesystem_default_ftruncate_directory,
2870        .fsync_h     = rtems_filesystem_default_fsync_or_fdatasync,
2871        .fdatasync_h = rtems_filesystem_default_fsync_or_fdatasync,
2872        .fcntl_h     = rtems_filesystem_default_fcntl,
2873        .kqfilter_h  = rtems_filesystem_default_kqfilter,
2874        .mmap_h      = rtems_filesystem_default_mmap,
2875        .poll_h      = rtems_filesystem_default_poll,
2876        .readv_h     = rtems_filesystem_default_readv,
2877        .writev_h    = rtems_filesystem_default_writev
2878};
2879
2880/* the link handlers table */
2881static const
2882struct _rtems_filesystem_file_handlers_r nfs_link_file_handlers = {
2883        .open_h      = rtems_filesystem_default_open,
2884        .close_h     = rtems_filesystem_default_close,
2885        .read_h      = rtems_filesystem_default_read,
2886        .write_h     = rtems_filesystem_default_write,
2887        .ioctl_h     = rtems_filesystem_default_ioctl,
2888        .lseek_h     = rtems_filesystem_default_lseek,
2889        .fstat_h     = nfs_fstat,
2890        .ftruncate_h = rtems_filesystem_default_ftruncate,
2891        .fsync_h     = rtems_filesystem_default_fsync_or_fdatasync,
2892        .fdatasync_h = rtems_filesystem_default_fsync_or_fdatasync,
2893        .fcntl_h     = rtems_filesystem_default_fcntl,
2894        .kqfilter_h  = rtems_filesystem_default_kqfilter,
2895        .mmap_h      = rtems_filesystem_default_mmap,
2896        .poll_h      = rtems_filesystem_default_poll,
2897        .readv_h     = rtems_filesystem_default_readv,
2898        .writev_h    = rtems_filesystem_default_writev
2899};
2900
2901/* we need a dummy driver entry table to get a
2902 * major number from the system
2903 */
2904static
2905rtems_device_driver nfs_initialize(
2906                rtems_device_major_number       major,
2907                rtems_device_minor_number       minor,
2908                void                                            *arg
2909)
2910{
2911        /* we don't really use this routine because
2912     * we cannot supply an argument (contrary
2913     * to what the 'arg' parameter suggests - it
2914     * is always set to 0 by the generics :-()
2915     * and because we don't want the user to
2916     * have to deal with the major number (which
2917     * OTOH is something WE are interested in. The
2918     * only reason for using this API was getting
2919     * a major number, after all).
2920     *
2921         * Something must be present, however, to
2922         * reserve a slot in the driver table.
2923         */
2924        return RTEMS_SUCCESSFUL;
2925}
2926
2927static rtems_driver_address_table       drvNfs = {
2928                nfs_initialize,
2929                0,                                      /* open    */
2930                0,                                      /* close   */
2931                0,                                      /* read    */
2932                0,                                      /* write   */
2933                0                                       /* control */
2934};
2935
2936/* Dump a list of the currently mounted NFS to a  file */
2937int
2938nfsMountsShow(FILE *f)
2939{
2940char    *mntpt = 0;
2941Nfs             nfs;
2942
2943        if (!f)
2944                f = stdout;
2945
2946        if ( !(mntpt=malloc(MAXPATHLEN)) ) {
2947                fprintf(stderr,"nfsMountsShow(): no memory\n");
2948                return -1;
2949        }
2950
2951        fprintf(f,"Currently Mounted NFS:\n");
2952
2953        LOCK(nfsGlob.llock);
2954
2955        for (nfs = nfsGlob.mounted_fs; nfs; nfs=nfs->next) {
2956                fprintf(f,"%s on ", nfs->mt_entry->dev);
2957                if (rtems_filesystem_resolve_location(mntpt, MAXPATHLEN, &nfs->mt_entry->mt_fs_root->location))
2958                        fprintf(f,"<UNABLE TO LOOKUP MOUNTPOINT>\n");
2959                else
2960                        fprintf(f,"%s\n",mntpt);
2961        }
2962
2963        UNLOCK(nfsGlob.llock);
2964
2965        free(mntpt);
2966        return 0;
2967}
2968
2969#if 0
2970CCJ_REMOVE_MOUNT
2971/* convenience wrapper
2972 *
2973 * NOTE: this routine calls NON-REENTRANT
2974 *       gethostbyname() if the host is
2975 *       not in 'dot' notation.
2976 */
2977int
2978nfsMount(char *uidhost, char *path, char *mntpoint)
2979{
2980struct stat                                                             st;
2981int                                                                             devl;
2982char                                                                    *host;
2983int                                                                             rval = -1;
2984char                                                                    *dev =  0;
2985
2986        if (!uidhost || !path || !mntpoint) {
2987                fprintf(stderr,"usage: nfsMount(""[uid.gid@]host"",""path"",""mountpoint"")\n");
2988                nfsMountsShow(stderr);
2989                return -1;
2990        }
2991
2992        if ( !(dev = malloc((devl=strlen(uidhost) + 20 + strlen(path)+1))) ) {
2993                fprintf(stderr,"nfsMount: out of memory\n");
2994                return -1;
2995        }
2996
2997        /* Try to create the mount point if nonexistent */
2998        if (stat(mntpoint, &st)) {
2999                if (ENOENT != errno) {
3000                        perror("nfsMount trying to create mount point - stat failed");
3001                        goto cleanup;
3002                } else if (mkdir(mntpoint,0777)) {
3003                        perror("nfsMount trying to create mount point");
3004                        goto cleanup;
3005                }
3006        }
3007
3008        if ( !(host=strchr(uidhost,UIDSEP)) ) {
3009                host = uidhost;
3010        } else {
3011                host++;
3012        }
3013
3014        if (isdigit((unsigned char)*host)) {
3015                /* avoid using gethostbyname */
3016                sprintf(dev,"%s:%s",uidhost,path);
3017        } else {
3018                struct hostent *h;
3019
3020                /* copy the uid part (hostname will be
3021                 * overwritten)
3022                 */
3023                strcpy(dev, uidhost);
3024
3025                /* NOTE NOTE NOTE: gethostbyname is NOT
3026                 * thread safe. This is UGLY
3027                 */
3028
3029/* BEGIN OF NON-THREAD SAFE REGION */
3030
3031                h = gethostbyname(host);
3032
3033                if ( !h ||
3034                         !inet_ntop( AF_INET,
3035                                             (struct in_addr*)h->h_addr_list[0],
3036                                                 dev  + (host - uidhost),
3037                                                 devl - (host - uidhost) )
3038                        ) {
3039                        fprintf(stderr,"nfsMount: host '%s' not found\n",host);
3040                        goto cleanup;
3041                }
3042
3043/* END OF NON-THREAD SAFE REGION */
3044
3045                /* append ':<path>' */
3046                strcat(dev,":");
3047                strcat(dev,path);
3048        }
3049
3050        printf("Trying to mount %s on %s\n",dev,mntpoint);
3051
3052        if (mount(dev,
3053                          mntpoint,
3054                          "nfs",
3055                          RTEMS_FILESYSTEM_READ_WRITE,
3056                          NULL)) {
3057                perror("nfsMount - mount");
3058                goto cleanup;
3059        }
3060
3061        rval = 0;
3062
3063cleanup:
3064        free(dev);
3065        return rval;
3066}
3067#endif
3068
3069/* HERE COMES A REALLY UGLY HACK */
3070
3071/* This is stupid; it is _very_ hard to find the path
3072 * leading to a rtems_filesystem_location_info_t node :-(
3073 * The only easy way is making the location the current
3074 * directory and issue a getcwd().
3075 * However, since we don't want to tamper with the
3076 * current directory, we must create a separate
3077 * task to do the job for us - sigh.
3078 */
3079
3080typedef struct ResolvePathArgRec_ {
3081        rtems_filesystem_location_info_t        *loc;   /* IN: location to resolve      */
3082        char                                                            *buf;   /* IN/OUT: buffer where to put the path */
3083        int                                                                     len;    /* IN: buffer length            */
3084        rtems_binary_semaphore                  sync;   /* IN: synchronization          */
3085        rtems_status_code                                       status; /* OUT: result                          */
3086} ResolvePathArgRec, *ResolvePathArg;
3087
3088static void
3089resolve_path(rtems_task_argument arg)
3090{
3091ResolvePathArg                                          rpa = (ResolvePathArg)arg;
3092rtems_filesystem_location_info_t        old;
3093
3094        /* IMPORTANT: let the helper task have its own libio environment (i.e. cwd) */
3095        if (RTEMS_SUCCESSFUL == (rpa->status = rtems_libio_set_private_env())) {
3096
3097                old = rtems_filesystem_current->location;
3098
3099                rtems_filesystem_current->location = *(rpa->loc);
3100
3101                if ( !getcwd(rpa->buf, rpa->len) )
3102                        rpa->status = RTEMS_UNSATISFIED;
3103
3104                /* must restore the cwd because 'freenode' will be called on it */
3105                rtems_filesystem_current->location = old;
3106        }
3107        rtems_binary_semaphore_post(&rpa->sync);
3108        rtems_task_exit();
3109}
3110
3111
3112/* a utility routine to find the path leading to a
3113 * rtems_filesystem_location_info_t node
3114 *
3115 * INPUT: 'loc' and a buffer 'buf' (length 'len') to hold the
3116 *        path.
3117 * OUTPUT: path copied into 'buf'
3118 *
3119 * RETURNS: 0 on success, RTEMS error code on error.
3120 */
3121rtems_status_code
3122rtems_filesystem_resolve_location(char *buf, int len, rtems_filesystem_location_info_t *loc)
3123{
3124ResolvePathArgRec       arg;
3125rtems_id                        tid = 0;
3126rtems_task_priority     pri;
3127rtems_status_code       status;
3128
3129        arg.loc  = loc;
3130        arg.buf  = buf;
3131        arg.len  = len;
3132
3133        rtems_binary_semaphore_init(&arg.sync, "NFSress");
3134
3135        rtems_task_set_priority(RTEMS_SELF, RTEMS_CURRENT_PRIORITY, &pri);
3136
3137        status = rtems_task_create(
3138                                        rtems_build_name('r','e','s','s'),
3139                                        pri,
3140                                        RTEMS_MINIMUM_STACK_SIZE + 50000,
3141                                        RTEMS_DEFAULT_MODES,
3142                                        RTEMS_DEFAULT_ATTRIBUTES,
3143                                        &tid);
3144
3145        if (RTEMS_SUCCESSFUL != status)
3146                goto cleanup;
3147
3148        status = rtems_task_start(tid, resolve_path, (rtems_task_argument)&arg);
3149
3150        if (RTEMS_SUCCESSFUL != status) {
3151                rtems_task_delete(tid);
3152                goto cleanup;
3153        }
3154
3155
3156        /* synchronize with the helper task */
3157        rtems_binary_semaphore_wait(&arg.sync);
3158
3159        status = arg.status;
3160
3161cleanup:
3162        rtems_binary_semaphore_destroy(&arg.sync);
3163
3164        return status;
3165}
3166
3167int
3168nfsSetTimeout(uint32_t timeout_ms)
3169{
3170rtems_interrupt_lock_context lock_context;
3171uint32_t                  s,us;
3172
3173        if ( timeout_ms > 100000 ) {
3174                /* out of range */
3175                return -1;
3176        }
3177
3178        s  = timeout_ms/1000;
3179        us = (timeout_ms % 1000) * 1000;
3180
3181        NFS_GLOBAL_ACQUIRE(&lock_context);
3182        _nfscalltimeout.tv_sec  = s;
3183        _nfscalltimeout.tv_usec = us;
3184        NFS_GLOBAL_RELEASE(&lock_context);
3185
3186        return 0;
3187}
3188
3189uint32_t
3190nfsGetTimeout( void )
3191{
3192rtems_interrupt_lock_context lock_context;
3193uint32_t              s,us;
3194        NFS_GLOBAL_ACQUIRE(&lock_context);
3195        s  = _nfscalltimeout.tv_sec;
3196        us = _nfscalltimeout.tv_usec;
3197        NFS_GLOBAL_RELEASE(&lock_context);
3198        return s*1000 + us/1000;
3199}
Note: See TracBrowser for help on using the repository browser.