]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/gfs.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / sys / cddl / contrib / opensolaris / uts / common / fs / gfs.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /* Portions Copyright 2007 Shivakumar GN */
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26
27 #pragma ident   "%Z%%M% %I%     %E% SMI"
28
29 #include <sys/types.h>
30 #include <sys/cmn_err.h>
31 #include <sys/debug.h>
32 #include <sys/dirent.h>
33 #include <sys/kmem.h>
34 #include <sys/mman.h>
35 #include <sys/mutex.h>
36 #include <sys/sysmacros.h>
37 #include <sys/systm.h>
38 #include <sys/sunddi.h>
39 #include <sys/uio.h>
40 #include <sys/vfs.h>
41 #include <sys/vnode.h>
42 #include <sys/cred.h>
43 #include <sys/kdb.h>
44
45 #include <sys/gfs.h>
46
47 /*
48  * Generic pseudo-filesystem routines.
49  *
50  * There are significant similarities between the implementation of certain file
51  * system entry points across different filesystems.  While one could attempt to
52  * "choke up on the bat" and incorporate common functionality into a VOP
53  * preamble or postamble, such an approach is limited in the benefit it can
54  * provide.  In this file we instead define a toolkit of routines which can be
55  * called from a filesystem (with in-kernel pseudo-filesystems being the focus
56  * of the exercise) in a more component-like fashion.
57  *
58  * There are three basic classes of routines:
59  *
60  * 1) Lowlevel support routines
61  *
62  *    These routines are designed to play a support role for existing
63  *    pseudo-filesystems (such as procfs).  They simplify common tasks,
64  *    without forcing the filesystem to hand over management to GFS.  The
65  *    routines covered are:
66  *
67  *      gfs_readdir_init()
68  *      gfs_readdir_emit()
69  *      gfs_readdir_emitn()
70  *      gfs_readdir_pred()
71  *      gfs_readdir_fini()
72  *      gfs_lookup_dot()
73  *
74  * 2) Complete GFS management
75  *
76  *    These routines take a more active role in management of the
77  *    pseudo-filesystem.  They handle the relationship between vnode private
78  *    data and VFS data, as well as the relationship between vnodes in the
79  *    directory hierarchy.
80  *
81  *    In order to use these interfaces, the first member of every private
82  *    v_data must be a gfs_file_t or a gfs_dir_t.  This hands over all control
83  *    to GFS.
84  *
85  *      gfs_file_create()
86  *      gfs_dir_create()
87  *      gfs_root_create()
88  *
89  *      gfs_file_inactive()
90  *      gfs_dir_inactive()
91  *      gfs_dir_lookup()
92  *      gfs_dir_readdir()
93  *
94  *      gfs_vop_inactive()
95  *      gfs_vop_lookup()
96  *      gfs_vop_readdir()
97  *      gfs_vop_map()
98  *
99  * 3) Single File pseudo-filesystems
100  *
101  *    This routine creates a rooted file to be overlayed ontop of another
102  *    file in the physical filespace.
103  *
104  *    Note that the parent is NULL (actually the vfs), but there is nothing
105  *    technically keeping such a file from utilizing the "Complete GFS
106  *    management" set of routines.
107  *
108  *      gfs_root_create_file()
109  */
110
111 /*
112  * Low level directory routines
113  *
114  * These routines provide some simple abstractions for reading directories.
115  * They are designed to be used by existing pseudo filesystems (namely procfs)
116  * that already have a complicated management infrastructure.
117  */
118
119 /*
120  * gfs_get_parent_ino: used to obtain a parent inode number and the
121  * inode number of the given vnode in preparation for calling gfs_readdir_init.
122  */
123 int
124 gfs_get_parent_ino(vnode_t *dvp, cred_t *cr, caller_context_t *ct,
125     ino64_t *pino, ino64_t *ino)
126 {
127         vnode_t *parent;
128         gfs_dir_t *dp = dvp->v_data;
129         int error;
130
131         *ino = dp->gfsd_file.gfs_ino;
132         parent = dp->gfsd_file.gfs_parent;
133
134         if (parent == NULL) {
135                 *pino = *ino;           /* root of filesystem */
136         } else if (dvp->v_flag & V_XATTRDIR) {
137 #ifdef TODO
138                 vattr_t va;
139
140                 va.va_mask = AT_NODEID;
141                 error = VOP_GETATTR(parent, &va, 0, cr, ct);
142                 if (error)
143                         return (error);
144                 *pino = va.va_nodeid;
145 #else
146                 panic("%s:%u: not implemented", __func__, __LINE__);
147 #endif
148         } else {
149                 *pino = ((gfs_file_t *)(parent->v_data))->gfs_ino;
150         }
151
152         return (0);
153 }
154
155 /*
156  * gfs_readdir_init: initiate a generic readdir
157  *   st         - a pointer to an uninitialized gfs_readdir_state_t structure
158  *   name_max   - the directory's maximum file name length
159  *   ureclen    - the exported file-space record length (1 for non-legacy FSs)
160  *   uiop       - the uiop passed to readdir
161  *   parent     - the parent directory's inode
162  *   self       - this directory's inode
163  *   flags      - flags from VOP_READDIR
164  *
165  * Returns 0 or a non-zero errno.
166  *
167  * Typical VOP_READDIR usage of gfs_readdir_*:
168  *
169  *      if ((error = gfs_readdir_init(...)) != 0)
170  *              return (error);
171  *      eof = 0;
172  *      while ((error = gfs_readdir_pred(..., &voffset)) != 0) {
173  *              if (!consumer_entry_at(voffset))
174  *                      voffset = consumer_next_entry(voffset);
175  *              if (consumer_eof(voffset)) {
176  *                      eof = 1
177  *                      break;
178  *              }
179  *              if ((error = gfs_readdir_emit(..., voffset,
180  *                  consumer_ino(voffset), consumer_name(voffset))) != 0)
181  *                      break;
182  *      }
183  *      return (gfs_readdir_fini(..., error, eofp, eof));
184  *
185  * As you can see, a zero result from gfs_readdir_pred() or
186  * gfs_readdir_emit() indicates that processing should continue,
187  * whereas a non-zero result indicates that the loop should terminate.
188  * Most consumers need do nothing more than let gfs_readdir_fini()
189  * determine what the cause of failure was and return the appropriate
190  * value.
191  */
192 int
193 gfs_readdir_init(gfs_readdir_state_t *st, int name_max, int ureclen,
194     uio_t *uiop, ino64_t parent, ino64_t self, int flags)
195 {
196         size_t dirent_size;
197
198         if (uiop->uio_loffset < 0 || uiop->uio_resid <= 0 ||
199             (uiop->uio_loffset % ureclen) != 0)
200                 return (EINVAL);
201
202         st->grd_ureclen = ureclen;
203         st->grd_oresid = uiop->uio_resid;
204         st->grd_namlen = name_max;
205         if (flags & V_RDDIR_ENTFLAGS)
206                 dirent_size = EDIRENT_RECLEN(st->grd_namlen);
207         else
208                 dirent_size = DIRENT64_RECLEN(st->grd_namlen);
209         st->grd_dirent = kmem_zalloc(dirent_size, KM_SLEEP);
210         st->grd_parent = parent;
211         st->grd_self = self;
212         st->grd_flags = flags;
213
214         return (0);
215 }
216
217 /*
218  * gfs_readdir_emit_int: internal routine to emit directory entry
219  *
220  *   st         - the current readdir state, which must have d_ino/ed_ino
221  *                and d_name/ed_name set
222  *   uiop       - caller-supplied uio pointer
223  *   next       - the offset of the next entry
224  */
225 static int
226 gfs_readdir_emit_int(gfs_readdir_state_t *st, uio_t *uiop, offset_t next,
227     int *ncookies, u_long **cookies)
228 {
229         int reclen, namlen;
230         dirent64_t *dp;
231         edirent_t *edp;
232
233         if (st->grd_flags & V_RDDIR_ENTFLAGS) {
234                 edp = st->grd_dirent;
235                 namlen = strlen(edp->ed_name);
236                 reclen = EDIRENT_RECLEN(namlen);
237         } else {
238                 dp = st->grd_dirent;
239                 namlen = strlen(dp->d_name);
240                 reclen = DIRENT64_RECLEN(namlen);
241         }
242
243         if (reclen > uiop->uio_resid) {
244                 /*
245                  * Error if no entries were returned yet
246                  */
247                 if (uiop->uio_resid == st->grd_oresid)
248                         return (EINVAL);
249                 return (-1);
250         }
251
252         if (st->grd_flags & V_RDDIR_ENTFLAGS) {
253                 edp->ed_off = next;
254                 edp->ed_reclen = (ushort_t)reclen;
255         } else {
256                 /* XXX: This can change in the future. */
257                 dp->d_reclen = (ushort_t)reclen;
258                 dp->d_type = DT_DIR;
259                 dp->d_namlen = namlen;
260         }
261
262         if (uiomove((caddr_t)st->grd_dirent, reclen, UIO_READ, uiop))
263                 return (EFAULT);
264
265         uiop->uio_loffset = next;
266         if (*cookies != NULL) {
267                 **cookies = next;
268                 (*cookies)++;
269                 (*ncookies)--;
270                 KASSERT(*ncookies >= 0, ("ncookies=%d", *ncookies));
271         }
272
273         return (0);
274 }
275
276 /*
277  * gfs_readdir_emit: emit a directory entry
278  *   voff       - the virtual offset (obtained from gfs_readdir_pred)
279  *   ino        - the entry's inode
280  *   name       - the entry's name
281  *   eflags     - value for ed_eflags (if processing edirent_t)
282  *
283  * Returns a 0 on success, a non-zero errno on failure, or -1 if the
284  * readdir loop should terminate.  A non-zero result (either errno or
285  * -1) from this function is typically passed directly to
286  * gfs_readdir_fini().
287  */
288 int
289 gfs_readdir_emit(gfs_readdir_state_t *st, uio_t *uiop, offset_t voff,
290     ino64_t ino, const char *name, int eflags, int *ncookies, u_long **cookies)
291 {
292         offset_t off = (voff + 2) * st->grd_ureclen;
293
294         if (st->grd_flags & V_RDDIR_ENTFLAGS) {
295                 edirent_t *edp = st->grd_dirent;
296
297                 edp->ed_ino = ino;
298                 (void) strncpy(edp->ed_name, name, st->grd_namlen);
299                 edp->ed_eflags = eflags;
300         } else {
301                 dirent64_t *dp = st->grd_dirent;
302
303                 dp->d_ino = ino;
304                 (void) strncpy(dp->d_name, name, st->grd_namlen);
305         }
306
307         /*
308          * Inter-entry offsets are invalid, so we assume a record size of
309          * grd_ureclen and explicitly set the offset appropriately.
310          */
311         return (gfs_readdir_emit_int(st, uiop, off + st->grd_ureclen, ncookies,
312             cookies));
313 }
314
315 /*
316  * gfs_readdir_pred: readdir loop predicate
317  *   voffp - a pointer in which the next virtual offset should be stored
318  *
319  * Returns a 0 on success, a non-zero errno on failure, or -1 if the
320  * readdir loop should terminate.  A non-zero result (either errno or
321  * -1) from this function is typically passed directly to
322  * gfs_readdir_fini().
323  */
324 int
325 gfs_readdir_pred(gfs_readdir_state_t *st, uio_t *uiop, offset_t *voffp,
326     int *ncookies, u_long **cookies)
327 {
328         offset_t off, voff;
329         int error;
330
331 top:
332         if (uiop->uio_resid <= 0)
333                 return (-1);
334
335         off = uiop->uio_loffset / st->grd_ureclen;
336         voff = off - 2;
337         if (off == 0) {
338                 if ((error = gfs_readdir_emit(st, uiop, voff, st->grd_self,
339                     ".", 0, ncookies, cookies)) == 0)
340                         goto top;
341         } else if (off == 1) {
342                 if ((error = gfs_readdir_emit(st, uiop, voff, st->grd_parent,
343                     "..", 0, ncookies, cookies)) == 0)
344                         goto top;
345         } else {
346                 *voffp = voff;
347                 return (0);
348         }
349
350         return (error);
351 }
352
353 /*
354  * gfs_readdir_fini: generic readdir cleanup
355  *   error      - if positive, an error to return
356  *   eofp       - the eofp passed to readdir
357  *   eof        - the eof value
358  *
359  * Returns a 0 on success, a non-zero errno on failure.  This result
360  * should be returned from readdir.
361  */
362 int
363 gfs_readdir_fini(gfs_readdir_state_t *st, int error, int *eofp, int eof)
364 {
365         size_t dirent_size;
366
367         if (st->grd_flags & V_RDDIR_ENTFLAGS)
368                 dirent_size = EDIRENT_RECLEN(st->grd_namlen);
369         else
370                 dirent_size = DIRENT64_RECLEN(st->grd_namlen);
371         kmem_free(st->grd_dirent, dirent_size);
372         if (error > 0)
373                 return (error);
374         if (eofp)
375                 *eofp = eof;
376         return (0);
377 }
378
379 /*
380  * gfs_lookup_dot
381  *
382  * Performs a basic check for "." and ".." directory entries.
383  */
384 int
385 gfs_lookup_dot(vnode_t **vpp, vnode_t *dvp, vnode_t *pvp, const char *nm)
386 {
387         if (*nm == '\0' || strcmp(nm, ".") == 0) {
388                 VN_HOLD(dvp);
389                 *vpp = dvp;
390                 return (0);
391         } else if (strcmp(nm, "..") == 0) {
392                 if (pvp == NULL) {
393                         ASSERT(dvp->v_flag & VROOT);
394                         VN_HOLD(dvp);
395                         *vpp = dvp;
396                 } else {
397                         VN_HOLD(pvp);
398                         *vpp = pvp;
399                 }
400                 vn_lock(*vpp, LK_EXCLUSIVE | LK_RETRY);
401                 return (0);
402         }
403
404         return (-1);
405 }
406
407 /*
408  * gfs_file_create(): create a new GFS file
409  *
410  *   size       - size of private data structure (v_data)
411  *   pvp        - parent vnode (GFS directory)
412  *   ops        - vnode operations vector
413  *
414  * In order to use this interface, the parent vnode must have been created by
415  * gfs_dir_create(), and the private data stored in v_data must have a
416  * 'gfs_file_t' as its first field.
417  *
418  * Given these constraints, this routine will automatically:
419  *
420  *      - Allocate v_data for the vnode
421  *      - Initialize necessary fields in the vnode
422  *      - Hold the parent
423  */
424 vnode_t *
425 gfs_file_create(size_t size, vnode_t *pvp, vfs_t *vfsp, vnodeops_t *ops)
426 {
427         gfs_file_t *fp;
428         vnode_t *vp;
429         int error;
430
431         /*
432          * Allocate vnode and internal data structure
433          */
434         fp = kmem_zalloc(size, KM_SLEEP);
435         error = getnewvnode("zfs", vfsp, ops, &vp);
436         ASSERT(error == 0);
437         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
438         vp->v_data = (caddr_t)fp;
439
440         /*
441          * Set up various pointers
442          */
443         fp->gfs_vnode = vp;
444         fp->gfs_parent = pvp;
445         fp->gfs_size = size;
446         fp->gfs_type = GFS_FILE;
447
448         vp->v_vflag |= VV_FORCEINSMQ;
449         error = insmntque(vp, vfsp);
450         vp->v_vflag &= ~VV_FORCEINSMQ;
451         KASSERT(error == 0, ("insmntque() failed: error %d", error));
452
453         /*
454          * Initialize vnode and hold parent.
455          */
456         if (pvp)
457                 VN_HOLD(pvp);
458
459         return (vp);
460 }
461
462 /*
463  * gfs_dir_create: creates a new directory in the parent
464  *
465  *   size       - size of private data structure (v_data)
466  *   pvp        - parent vnode (GFS directory)
467  *   ops        - vnode operations vector
468  *   entries    - NULL-terminated list of static entries (if any)
469  *   maxlen     - maximum length of a directory entry
470  *   readdir_cb - readdir callback (see gfs_dir_readdir)
471  *   inode_cb   - inode callback (see gfs_dir_readdir)
472  *   lookup_cb  - lookup callback (see gfs_dir_lookup)
473  *
474  * In order to use this function, the first member of the private vnode
475  * structure (v_data) must be a gfs_dir_t.  For each directory, there are
476  * static entries, defined when the structure is initialized, and dynamic
477  * entries, retrieved through callbacks.
478  *
479  * If a directory has static entries, then it must supply a inode callback,
480  * which will compute the inode number based on the parent and the index.
481  * For a directory with dynamic entries, the caller must supply a readdir
482  * callback and a lookup callback.  If a static lookup fails, we fall back to
483  * the supplied lookup callback, if any.
484  *
485  * This function also performs the same initialization as gfs_file_create().
486  */
487 vnode_t *
488 gfs_dir_create(size_t struct_size, vnode_t *pvp, vfs_t *vfsp, vnodeops_t *ops,
489     gfs_dirent_t *entries, gfs_inode_cb inode_cb, int maxlen,
490     gfs_readdir_cb readdir_cb, gfs_lookup_cb lookup_cb)
491 {
492         vnode_t *vp;
493         gfs_dir_t *dp;
494         gfs_dirent_t *de;
495
496         vp = gfs_file_create(struct_size, pvp, vfsp, ops);
497         vp->v_type = VDIR;
498
499         dp = vp->v_data;
500         dp->gfsd_file.gfs_type = GFS_DIR;
501         dp->gfsd_maxlen = maxlen;
502
503         if (entries != NULL) {
504                 for (de = entries; de->gfse_name != NULL; de++)
505                         dp->gfsd_nstatic++;
506
507                 dp->gfsd_static = kmem_alloc(
508                     dp->gfsd_nstatic * sizeof (gfs_dirent_t), KM_SLEEP);
509                 bcopy(entries, dp->gfsd_static,
510                     dp->gfsd_nstatic * sizeof (gfs_dirent_t));
511         }
512
513         dp->gfsd_readdir = readdir_cb;
514         dp->gfsd_lookup = lookup_cb;
515         dp->gfsd_inode = inode_cb;
516
517         mutex_init(&dp->gfsd_lock, NULL, MUTEX_DEFAULT, NULL);
518
519         return (vp);
520 }
521
522 /*
523  * gfs_root_create(): create a root vnode for a GFS filesystem
524  *
525  * Similar to gfs_dir_create(), this creates a root vnode for a filesystem.  The
526  * only difference is that it takes a vfs_t instead of a vnode_t as its parent.
527  */
528 vnode_t *
529 gfs_root_create(size_t size, vfs_t *vfsp, vnodeops_t *ops, ino64_t ino,
530     gfs_dirent_t *entries, gfs_inode_cb inode_cb, int maxlen,
531     gfs_readdir_cb readdir_cb, gfs_lookup_cb lookup_cb)
532 {
533         vnode_t *vp;
534
535         VFS_HOLD(vfsp);
536         vp = gfs_dir_create(size, NULL, vfsp, ops, entries, inode_cb,
537             maxlen, readdir_cb, lookup_cb);
538         /* Manually set the inode */
539         ((gfs_file_t *)vp->v_data)->gfs_ino = ino;
540         vp->v_flag |= VROOT;
541
542         return (vp);
543 }
544
545 /*
546  * gfs_file_inactive()
547  *
548  * Called from the VOP_INACTIVE() routine.  If necessary, this routine will
549  * remove the given vnode from the parent directory and clean up any references
550  * in the VFS layer.
551  *
552  * If the vnode was not removed (due to a race with vget), then NULL is
553  * returned.  Otherwise, a pointer to the private data is returned.
554  */
555 void *
556 gfs_file_inactive(vnode_t *vp)
557 {
558         int i;
559         gfs_dirent_t *ge = NULL;
560         gfs_file_t *fp = vp->v_data;
561         gfs_dir_t *dp = NULL;
562         void *data;
563
564         if (fp->gfs_parent == NULL || (vp->v_flag & V_XATTRDIR))
565                 goto found;
566
567         /*
568          * XXX cope with a FreeBSD-specific race wherein the parent's
569          * snapshot data can be freed before the parent is
570          */
571         if ((dp = fp->gfs_parent->v_data) == NULL)
572                 return (NULL);
573                 
574         /*
575          * First, see if this vnode is cached in the parent.
576          */
577         gfs_dir_lock(dp);
578
579         /*
580          * Find it in the set of static entries.
581          */
582         for (i = 0; i < dp->gfsd_nstatic; i++)  {
583                 ge = &dp->gfsd_static[i];
584
585                 if (ge->gfse_vnode == vp)
586                         goto found;
587         }
588
589         /*
590          * If 'ge' is NULL, then it is a dynamic entry.
591          */
592         ge = NULL;
593
594 found:
595         if (vp->v_flag & V_XATTRDIR)
596                 VI_LOCK(fp->gfs_parent);
597         VI_LOCK(vp);
598         /*
599          * Really remove this vnode
600          */
601         data = vp->v_data;
602         if (ge != NULL) {
603                 /*
604                  * If this was a statically cached entry, simply set the
605                  * cached vnode to NULL.
606                  */
607                 ge->gfse_vnode = NULL;
608         }
609         VI_UNLOCK(vp);
610
611         /*
612          * Free vnode and release parent
613          */
614         if (fp->gfs_parent) {
615                 if (dp)
616                         gfs_dir_unlock(dp);
617                 VI_LOCK(fp->gfs_parent);
618                 fp->gfs_parent->v_usecount--;
619                 VI_UNLOCK(fp->gfs_parent);
620         } else {
621                 ASSERT(vp->v_vfsp != NULL);
622                 VFS_RELE(vp->v_vfsp);
623         }
624         if (vp->v_flag & V_XATTRDIR)
625                 VI_UNLOCK(fp->gfs_parent);
626
627         return (data);
628 }
629
630 /*
631  * gfs_dir_inactive()
632  *
633  * Same as above, but for directories.
634  */
635 void *
636 gfs_dir_inactive(vnode_t *vp)
637 {
638         gfs_dir_t *dp;
639
640         ASSERT(vp->v_type == VDIR);
641
642         if ((dp = gfs_file_inactive(vp)) != NULL) {
643                 mutex_destroy(&dp->gfsd_lock);
644                 if (dp->gfsd_nstatic)
645                         kmem_free(dp->gfsd_static,
646                             dp->gfsd_nstatic * sizeof (gfs_dirent_t));
647         }
648
649         return (dp);
650 }
651
652 /*
653  * gfs_dir_lookup_dynamic()
654  *
655  * This routine looks up the provided name amongst the dynamic entries
656  * in the gfs directory and returns the corresponding vnode, if found.
657  *
658  * The gfs directory is expected to be locked by the caller prior to
659  * calling this function.  The directory will be unlocked during the
660  * execution of this function, but will be locked upon return from the
661  * function.  This function returns 0 on success, non-zero on error.
662  *
663  * The dynamic lookups are performed by invoking the lookup
664  * callback, which is passed to this function as the first argument.
665  * The arguments to the callback are:
666  *
667  * int gfs_lookup_cb(vnode_t *pvp, const char *nm, vnode_t **vpp, cred_t *cr,
668  *     int flags, int *deflgs, pathname_t *rpnp);
669  *
670  *      pvp     - parent vnode
671  *      nm      - name of entry
672  *      vpp     - pointer to resulting vnode
673  *      cr      - pointer to cred
674  *      flags   - flags value from lookup request
675  *              ignored here; currently only used to request
676  *              insensitive lookups
677  *      direntflgs - output parameter, directory entry flags
678  *              ignored here; currently only used to indicate a lookup
679  *              has more than one possible match when case is not considered
680  *      realpnp - output parameter, real pathname
681  *              ignored here; when lookup was performed case-insensitively,
682  *              this field contains the "real" name of the file.
683  *
684  *      Returns 0 on success, non-zero on error.
685  */
686 static int
687 gfs_dir_lookup_dynamic(gfs_lookup_cb callback, gfs_dir_t *dp,
688     const char *nm, vnode_t *dvp, vnode_t **vpp, cred_t *cr, int flags,
689     int *direntflags, pathname_t *realpnp)
690 {
691         gfs_file_t *fp;
692         ino64_t ino;
693         int ret;
694
695         ASSERT(GFS_DIR_LOCKED(dp));
696
697         /*
698          * Drop the directory lock, as the lookup routine
699          * will need to allocate memory, or otherwise deadlock on this
700          * directory.
701          */
702         gfs_dir_unlock(dp);
703         ret = callback(dvp, nm, vpp, &ino, cr, flags, direntflags, realpnp);
704         gfs_dir_lock(dp);
705
706         /*
707          * The callback for extended attributes returns a vnode
708          * with v_data from an underlying fs.
709          */
710         if (ret == 0 && !IS_XATTRDIR(dvp)) {
711                 fp = (gfs_file_t *)((*vpp)->v_data);
712                 fp->gfs_index = -1;
713                 fp->gfs_ino = ino;
714         }
715
716         return (ret);
717 }
718
719 /*
720  * gfs_dir_lookup_static()
721  *
722  * This routine looks up the provided name amongst the static entries
723  * in the gfs directory and returns the corresponding vnode, if found.
724  * The first argument to the function is a pointer to the comparison
725  * function this function should use to decide if names are a match.
726  *
727  * If a match is found, and GFS_CACHE_VNODE is set and the vnode
728  * exists, we simply return the existing vnode.  Otherwise, we call
729  * the static entry's callback routine, caching the result if
730  * necessary.  If the idx pointer argument is non-NULL, we use it to
731  * return the index of the matching static entry.
732  *
733  * The gfs directory is expected to be locked by the caller prior to calling
734  * this function.  The directory may be unlocked during the execution of
735  * this function, but will be locked upon return from the function.
736  *
737  * This function returns 0 if a match is found, ENOENT if not.
738  */
739 static int
740 gfs_dir_lookup_static(int (*compare)(const char *, const char *),
741     gfs_dir_t *dp, const char *nm, vnode_t *dvp, int *idx,
742     vnode_t **vpp, pathname_t *rpnp)
743 {
744         gfs_dirent_t *ge;
745         vnode_t *vp = NULL;
746         int i;
747
748         ASSERT(GFS_DIR_LOCKED(dp));
749
750         /*
751          * Search static entries.
752          */
753         for (i = 0; i < dp->gfsd_nstatic; i++) {
754                 ge = &dp->gfsd_static[i];
755
756                 if (compare(ge->gfse_name, nm) == 0) {
757                         if (rpnp)
758                                 (void) strlcpy(rpnp->pn_buf, ge->gfse_name,
759                                     rpnp->pn_bufsize);
760
761                         if (ge->gfse_vnode) {
762                                 ASSERT(ge->gfse_flags & GFS_CACHE_VNODE);
763                                 vp = ge->gfse_vnode;
764                                 VN_HOLD(vp);
765                                 break;
766                         }
767
768                         /*
769                          * We drop the directory lock, as the constructor will
770                          * need to do KM_SLEEP allocations.  If we return from
771                          * the constructor only to find that a parallel
772                          * operation has completed, and GFS_CACHE_VNODE is set
773                          * for this entry, we discard the result in favor of
774                          * the cached vnode.
775                          */
776                         gfs_dir_unlock(dp);
777                         vp = ge->gfse_ctor(dvp);
778                         gfs_dir_lock(dp);
779
780                         ((gfs_file_t *)vp->v_data)->gfs_index = i;
781
782                         /* Set the inode according to the callback. */
783                         ((gfs_file_t *)vp->v_data)->gfs_ino =
784                             dp->gfsd_inode(dvp, i);
785
786                         if (ge->gfse_flags & GFS_CACHE_VNODE) {
787                                 if (ge->gfse_vnode == NULL) {
788                                         ge->gfse_vnode = vp;
789                                 } else {
790                                         /*
791                                          * A parallel constructor beat us to it;
792                                          * return existing vnode.  We have to be
793                                          * careful because we can't release the
794                                          * current vnode while holding the
795                                          * directory lock; its inactive routine
796                                          * will try to lock this directory.
797                                          */
798                                         vnode_t *oldvp = vp;
799                                         vp = ge->gfse_vnode;
800                                         VN_HOLD(vp);
801
802                                         gfs_dir_unlock(dp);
803                                         VN_RELE(oldvp);
804                                         gfs_dir_lock(dp);
805                                 }
806                         }
807                         break;
808                 }
809         }
810
811         if (vp == NULL)
812                 return (ENOENT);
813         else if (idx)
814                 *idx = i;
815         *vpp = vp;
816         return (0);
817 }
818
819 /*
820  * gfs_dir_lookup()
821  *
822  * Looks up the given name in the directory and returns the corresponding
823  * vnode, if found.
824  *
825  * First, we search statically defined entries, if any, with a call to
826  * gfs_dir_lookup_static().  If no static entry is found, and we have
827  * a callback function we try a dynamic lookup via gfs_dir_lookup_dynamic().
828  *
829  * This function returns 0 on success, non-zero on error.
830  */
831 int
832 gfs_dir_lookup(vnode_t *dvp, const char *nm, vnode_t **vpp, cred_t *cr,
833     int flags, int *direntflags, pathname_t *realpnp)
834 {
835         gfs_dir_t *dp = dvp->v_data;
836         boolean_t casecheck;
837         vnode_t *dynvp = NULL;
838         vnode_t *vp = NULL;
839         int (*compare)(const char *, const char *);
840         int error, idx;
841
842         ASSERT(dvp->v_type == VDIR);
843
844         if (gfs_lookup_dot(vpp, dvp, dp->gfsd_file.gfs_parent, nm) == 0)
845                 return (0);
846
847         casecheck = (flags & FIGNORECASE) != 0 && direntflags != NULL;
848         if (vfs_has_feature(dvp->v_vfsp, VFSFT_NOCASESENSITIVE) ||
849             (flags & FIGNORECASE))
850                 compare = strcasecmp;
851         else
852                 compare = strcmp;
853
854         gfs_dir_lock(dp);
855
856         error = gfs_dir_lookup_static(compare, dp, nm, dvp, &idx, &vp, realpnp);
857
858         if (vp && casecheck) {
859                 gfs_dirent_t *ge;
860                 int i;
861
862                 for (i = idx + 1; i < dp->gfsd_nstatic; i++) {
863                         ge = &dp->gfsd_static[i];
864
865                         if (strcasecmp(ge->gfse_name, nm) == 0) {
866                                 *direntflags |= ED_CASE_CONFLICT;
867                                 goto out;
868                         }
869                 }
870         }
871
872         if ((error || casecheck) && dp->gfsd_lookup)
873                 error = gfs_dir_lookup_dynamic(dp->gfsd_lookup, dp, nm, dvp,
874                     &dynvp, cr, flags, direntflags, vp ? NULL : realpnp);
875
876         if (vp && dynvp) {
877                 /* static and dynamic entries are case-insensitive conflict */
878                 ASSERT(casecheck);
879                 *direntflags |= ED_CASE_CONFLICT;
880                 VN_RELE(dynvp);
881         } else if (vp == NULL) {
882                 vp = dynvp;
883         } else if (error == ENOENT) {
884                 error = 0;
885         } else if (error) {
886                 VN_RELE(vp);
887                 vp = NULL;
888         }
889
890 out:
891         gfs_dir_unlock(dp);
892
893         *vpp = vp;
894         return (error);
895 }
896
897 /*
898  * gfs_dir_readdir: does a readdir() on the given directory
899  *
900  *    dvp       - directory vnode
901  *    uiop      - uio structure
902  *    eofp      - eof pointer
903  *    data      - arbitrary data passed to readdir callback
904  *
905  * This routine does all the readdir() dirty work.  Even so, the caller must
906  * supply two callbacks in order to get full compatibility.
907  *
908  * If the directory contains static entries, an inode callback must be
909  * specified.  This avoids having to create every vnode and call VOP_GETATTR()
910  * when reading the directory.  This function has the following arguments:
911  *
912  *      ino_t gfs_inode_cb(vnode_t *vp, int index);
913  *
914  *      vp      - vnode for the directory
915  *      index   - index in original gfs_dirent_t array
916  *
917  *      Returns the inode number for the given entry.
918  *
919  * For directories with dynamic entries, a readdir callback must be provided.
920  * This is significantly more complex, thanks to the particulars of
921  * VOP_READDIR().
922  *
923  *      int gfs_readdir_cb(vnode_t *vp, void *dp, int *eofp,
924  *          offset_t *off, offset_t *nextoff, void *data, int flags)
925  *
926  *      vp      - directory vnode
927  *      dp      - directory entry, sized according to maxlen given to
928  *                gfs_dir_create().  callback must fill in d_name and
929  *                d_ino (if a dirent64_t), or ed_name, ed_ino, and ed_eflags
930  *                (if an edirent_t). edirent_t is used if V_RDDIR_ENTFLAGS
931  *                is set in 'flags'.
932  *      eofp    - callback must set to 1 when EOF has been reached
933  *      off     - on entry, the last offset read from the directory.  Callback
934  *                must set to the offset of the current entry, typically left
935  *                untouched.
936  *      nextoff - callback must set to offset of next entry.  Typically
937  *                (off + 1)
938  *      data    - caller-supplied data
939  *      flags   - VOP_READDIR flags
940  *
941  *      Return 0 on success, or error on failure.
942  */
943 int
944 gfs_dir_readdir(vnode_t *dvp, uio_t *uiop, int *eofp, int *ncookies,
945     u_long **cookies, void *data, cred_t *cr, int flags)
946 {
947         gfs_readdir_state_t gstate;
948         int error, eof = 0;
949         ino64_t ino, pino;
950         offset_t off, next;
951         gfs_dir_t *dp = dvp->v_data;
952
953         error = gfs_get_parent_ino(dvp, cr, NULL, &pino, &ino);
954         if (error)
955                 return (error);
956
957         if ((error = gfs_readdir_init(&gstate, dp->gfsd_maxlen, 1, uiop,
958             pino, ino, flags)) != 0)
959                 return (error);
960
961         while ((error = gfs_readdir_pred(&gstate, uiop, &off, ncookies,
962             cookies)) == 0 && !eof) {
963
964                 if (off >= 0 && off < dp->gfsd_nstatic) {
965                         ino = dp->gfsd_inode(dvp, off);
966
967                         if ((error = gfs_readdir_emit(&gstate, uiop,
968                             off, ino, dp->gfsd_static[off].gfse_name, 0,
969                             ncookies, cookies)) != 0)
970                                 break;
971
972                 } else if (dp->gfsd_readdir) {
973                         off -= dp->gfsd_nstatic;
974
975                         if ((error = dp->gfsd_readdir(dvp,
976                             gstate.grd_dirent, &eof, &off, &next,
977                             data, flags)) != 0 || eof)
978                                 break;
979
980                         off += dp->gfsd_nstatic + 2;
981                         next += dp->gfsd_nstatic + 2;
982
983                         if ((error = gfs_readdir_emit_int(&gstate, uiop,
984                             next, ncookies, cookies)) != 0)
985                                 break;
986                 } else {
987                         /*
988                          * Offset is beyond the end of the static entries, and
989                          * we have no dynamic entries.  Set EOF.
990                          */
991                         eof = 1;
992                 }
993         }
994
995         return (gfs_readdir_fini(&gstate, error, eofp, eof));
996 }
997
998 /*
999  * gfs_vop_lookup: VOP_LOOKUP() entry point
1000  *
1001  * For use directly in vnode ops table.  Given a GFS directory, calls
1002  * gfs_dir_lookup() as necessary.
1003  */
1004 /* ARGSUSED */
1005 int
1006 gfs_vop_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, pathname_t *pnp,
1007     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
1008     int *direntflags, pathname_t *realpnp)
1009 {
1010         return (gfs_dir_lookup(dvp, nm, vpp, cr, flags, direntflags, realpnp));
1011 }
1012
1013 /*
1014  * gfs_vop_readdir: VOP_READDIR() entry point
1015  *
1016  * For use directly in vnode ops table.  Given a GFS directory, calls
1017  * gfs_dir_readdir() as necessary.
1018  */
1019 /* ARGSUSED */
1020 int
1021 gfs_vop_readdir(ap)
1022         struct vop_readdir_args /* {
1023                 struct vnode *a_vp;
1024                 struct uio *a_uio;
1025                 struct ucred *a_cred;
1026                 int *a_eofflag;
1027                 int *ncookies;
1028                 u_long **a_cookies;
1029         } */ *ap;
1030 {
1031         vnode_t *vp = ap->a_vp;
1032         uio_t *uiop = ap->a_uio;
1033         cred_t *cr = ap->a_cred;
1034         int *eofp = ap->a_eofflag;
1035         int ncookies = 0;
1036         u_long *cookies = NULL;
1037         int error;
1038
1039         if (ap->a_ncookies) {
1040                 /*
1041                  * Minimum entry size is dirent size and 1 byte for a file name.
1042                  */
1043                 ncookies = uiop->uio_resid / (sizeof(struct dirent) - sizeof(((struct dirent *)NULL)->d_name) + 1);
1044                 cookies = malloc(ncookies * sizeof(u_long), M_TEMP, M_WAITOK);
1045                 *ap->a_cookies = cookies;
1046                 *ap->a_ncookies = ncookies;
1047         }
1048
1049         error = gfs_dir_readdir(vp, uiop, eofp, &ncookies, &cookies, NULL,
1050             cr, 0);
1051
1052         if (error == 0) {
1053                 /* Subtract unused cookies */
1054                 if (ap->a_ncookies)
1055                         *ap->a_ncookies -= ncookies;
1056         } else if (ap->a_ncookies) {
1057                 free(*ap->a_cookies, M_TEMP);
1058                 *ap->a_cookies = NULL;
1059                 *ap->a_ncookies = 0;
1060         }
1061
1062         return (error);
1063 }
1064
1065 /*
1066  * gfs_vop_inactive: VOP_INACTIVE() entry point
1067  *
1068  * Given a vnode that is a GFS file or directory, call gfs_file_inactive() or
1069  * gfs_dir_inactive() as necessary, and kmem_free()s associated private data.
1070  */
1071 /* ARGSUSED */
1072 int
1073 gfs_vop_inactive(ap)
1074         struct vop_inactive_args /* {
1075                 struct vnode *a_vp;
1076                 struct thread *a_td;
1077         } */ *ap;
1078 {
1079         vnode_t *vp = ap->a_vp;
1080         gfs_file_t *fp = vp->v_data;
1081
1082         if (fp->gfs_type == GFS_DIR)
1083                 gfs_dir_inactive(vp);
1084         else
1085                 gfs_file_inactive(vp);
1086
1087         VI_LOCK(vp);
1088         vp->v_data = NULL;
1089         VI_UNLOCK(vp);
1090         kmem_free(fp, fp->gfs_size);
1091
1092         return (0);
1093 }