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

4.115
Last change on this file since 2563410 was 2563410, checked in by Sebastian Huber <sebastian.huber@…>, on 03/13/12 at 08:22:11

Filesystem: Rename defines

o Removed RTEMS_LIBIO_PERMS_SEARCH.
o Renamed RTEMS_LIBIO_PERMS_READ in RTEMS_FS_PERMS_READ.
o Renamed RTEMS_LIBIO_PERMS_WRITE in RTEMS_FS_PERMS_WRITE.
o Renamed RTEMS_LIBIO_PERMS_EXEC in RTEMS_FS_PERMS_EXEC.
o Renamed RTEMS_LIBIO_FOLLOW_HARD_LINK in RTEMS_FS_FOLLOW_HARD_LINK.
o Renamed RTEMS_LIBIO_FOLLOW_SYM_LINK in RTEMS_FS_FOLLOW_SYM_LINK.
o Renamed RTEMS_LIBIO_MAKE in RTEMS_FS_MAKE.
o Renamed RTEMS_LIBIO_EXCLUSIVE in RTEMS_FS_EXCLUSIVE.
o Renamed RTEMS_LIBIO_ACCEPT_RESIDUAL_DELIMITERS in

RTEMS_FS_ACCEPT_RESIDUAL_DELIMITERS.

o Renamed RTEMS_LIBIO_REJECT_TERMINAL_DOT in
RTEMS_FS_REJECT_TERMINAL_DOT.

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