Fixed a use-after-free bug in zfs_zget().
[zfs.git] / module / zfs / zfs_znode.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 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24
25 /* Portions Copyright 2007 Jeremy Teo */
26
27 #ifdef _KERNEL
28 #include <sys/types.h>
29 #include <sys/param.h>
30 #include <sys/time.h>
31 #include <sys/systm.h>
32 #include <sys/sysmacros.h>
33 #include <sys/resource.h>
34 #include <sys/mntent.h>
35 #include <sys/mkdev.h>
36 #include <sys/u8_textprep.h>
37 #include <sys/dsl_dataset.h>
38 #include <sys/vfs.h>
39 #include <sys/vfs_opreg.h>
40 #include <sys/vnode.h>
41 #include <sys/file.h>
42 #include <sys/kmem.h>
43 #include <sys/errno.h>
44 #include <sys/unistd.h>
45 #include <sys/mode.h>
46 #include <sys/atomic.h>
47 #include <vm/pvn.h>
48 #include "fs/fs_subr.h"
49 #include <sys/zfs_dir.h>
50 #include <sys/zfs_acl.h>
51 #include <sys/zfs_ioctl.h>
52 #include <sys/zfs_rlock.h>
53 #include <sys/zfs_fuid.h>
54 #include <sys/zfs_vnops.h>
55 #include <sys/dnode.h>
56 #include <sys/fs/zfs.h>
57 #include <sys/kidmap.h>
58 #include <sys/zpl.h>
59 #endif /* _KERNEL */
60
61 #include <sys/dmu.h>
62 #include <sys/refcount.h>
63 #include <sys/stat.h>
64 #include <sys/zap.h>
65 #include <sys/zfs_znode.h>
66 #include <sys/sa.h>
67 #include <sys/zfs_sa.h>
68 #include <sys/zfs_stat.h>
69
70 #include "zfs_prop.h"
71 #include "zfs_comutil.h"
72
73 /*
74  * Define ZNODE_STATS to turn on statistic gathering. By default, it is only
75  * turned on when DEBUG is also defined.
76  */
77 #ifdef  DEBUG
78 #define ZNODE_STATS
79 #endif  /* DEBUG */
80
81 #ifdef  ZNODE_STATS
82 #define ZNODE_STAT_ADD(stat)                    ((stat)++)
83 #else
84 #define ZNODE_STAT_ADD(stat)                    /* nothing */
85 #endif  /* ZNODE_STATS */
86
87 /*
88  * Functions needed for userland (ie: libzpool) are not put under
89  * #ifdef_KERNEL; the rest of the functions have dependencies
90  * (such as VFS logic) that will not compile easily in userland.
91  */
92 #ifdef _KERNEL
93
94 static kmem_cache_t *znode_cache = NULL;
95
96 /*ARGSUSED*/
97 static int
98 zfs_znode_cache_constructor(void *buf, void *arg, int kmflags)
99 {
100         znode_t *zp = buf;
101
102         inode_init_once(ZTOI(zp));
103         list_link_init(&zp->z_link_node);
104
105         mutex_init(&zp->z_lock, NULL, MUTEX_DEFAULT, NULL);
106         rw_init(&zp->z_parent_lock, NULL, RW_DEFAULT, NULL);
107         rw_init(&zp->z_name_lock, NULL, RW_DEFAULT, NULL);
108         mutex_init(&zp->z_acl_lock, NULL, MUTEX_DEFAULT, NULL);
109
110         mutex_init(&zp->z_range_lock, NULL, MUTEX_DEFAULT, NULL);
111         avl_create(&zp->z_range_avl, zfs_range_compare,
112             sizeof (rl_t), offsetof(rl_t, r_node));
113
114         zp->z_dirlocks = NULL;
115         zp->z_acl_cached = NULL;
116         zp->z_moved = 0;
117         return (0);
118 }
119
120 /*ARGSUSED*/
121 static void
122 zfs_znode_cache_destructor(void *buf, void *arg)
123 {
124         znode_t *zp = buf;
125
126         ASSERT(!list_link_active(&zp->z_link_node));
127         mutex_destroy(&zp->z_lock);
128         rw_destroy(&zp->z_parent_lock);
129         rw_destroy(&zp->z_name_lock);
130         mutex_destroy(&zp->z_acl_lock);
131         avl_destroy(&zp->z_range_avl);
132         mutex_destroy(&zp->z_range_lock);
133
134         ASSERT(zp->z_dirlocks == NULL);
135         ASSERT(zp->z_acl_cached == NULL);
136 }
137
138 void
139 zfs_znode_init(void)
140 {
141         /*
142          * Initialize zcache
143          */
144         ASSERT(znode_cache == NULL);
145         znode_cache = kmem_cache_create("zfs_znode_cache",
146             sizeof (znode_t), 0, zfs_znode_cache_constructor,
147             zfs_znode_cache_destructor, NULL, NULL, NULL, KMC_KMEM);
148 }
149
150 void
151 zfs_znode_fini(void)
152 {
153         /*
154          * Cleanup zcache
155          */
156         if (znode_cache)
157                 kmem_cache_destroy(znode_cache);
158         znode_cache = NULL;
159 }
160
161 int
162 zfs_create_share_dir(zfs_sb_t *zsb, dmu_tx_t *tx)
163 {
164 #ifdef HAVE_SHARE
165         zfs_acl_ids_t acl_ids;
166         vattr_t vattr;
167         znode_t *sharezp;
168         vnode_t *vp;
169         znode_t *zp;
170         int error;
171
172         vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
173         vattr.va_mode = S_IFDIR | 0555;
174         vattr.va_uid = crgetuid(kcred);
175         vattr.va_gid = crgetgid(kcred);
176
177         sharezp = kmem_cache_alloc(znode_cache, KM_PUSHPAGE);
178         sharezp->z_moved = 0;
179         sharezp->z_unlinked = 0;
180         sharezp->z_atime_dirty = 0;
181         sharezp->z_zfsvfs = zfsvfs;
182         sharezp->z_is_sa = zfsvfs->z_use_sa;
183
184         vp = ZTOV(sharezp);
185         vn_reinit(vp);
186         vp->v_type = VDIR;
187
188         VERIFY(0 == zfs_acl_ids_create(sharezp, IS_ROOT_NODE, &vattr,
189             kcred, NULL, &acl_ids));
190         zfs_mknode(sharezp, &vattr, tx, kcred, IS_ROOT_NODE, &zp, &acl_ids);
191         ASSERT3P(zp, ==, sharezp);
192         ASSERT(!vn_in_dnlc(ZTOV(sharezp))); /* not valid to move */
193         POINTER_INVALIDATE(&sharezp->z_zfsvfs);
194         error = zap_add(zfsvfs->z_os, MASTER_NODE_OBJ,
195             ZFS_SHARES_DIR, 8, 1, &sharezp->z_id, tx);
196         zfsvfs->z_shares_dir = sharezp->z_id;
197
198         zfs_acl_ids_free(&acl_ids);
199         // ZTOV(sharezp)->v_count = 0;
200         sa_handle_destroy(sharezp->z_sa_hdl);
201         kmem_cache_free(znode_cache, sharezp);
202
203         return (error);
204 #else
205         return (0);
206 #endif /* HAVE_SHARE */
207 }
208
209 static void
210 zfs_znode_sa_init(zfs_sb_t *zsb, znode_t *zp,
211     dmu_buf_t *db, dmu_object_type_t obj_type, sa_handle_t *sa_hdl)
212 {
213         ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zsb, zp->z_id)));
214
215         mutex_enter(&zp->z_lock);
216
217         ASSERT(zp->z_sa_hdl == NULL);
218         ASSERT(zp->z_acl_cached == NULL);
219         if (sa_hdl == NULL) {
220                 VERIFY(0 == sa_handle_get_from_db(zsb->z_os, db, zp,
221                     SA_HDL_SHARED, &zp->z_sa_hdl));
222         } else {
223                 zp->z_sa_hdl = sa_hdl;
224                 sa_set_userp(sa_hdl, zp);
225         }
226
227         zp->z_is_sa = (obj_type == DMU_OT_SA) ? B_TRUE : B_FALSE;
228
229         mutex_exit(&zp->z_lock);
230 }
231
232 void
233 zfs_znode_dmu_fini(znode_t *zp)
234 {
235         ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(ZTOZSB(zp), zp->z_id)) ||
236             zp->z_unlinked ||
237             RW_WRITE_HELD(&ZTOZSB(zp)->z_teardown_inactive_lock));
238
239         sa_handle_destroy(zp->z_sa_hdl);
240         zp->z_sa_hdl = NULL;
241 }
242
243 /*
244  * Called by new_inode() to allocate a new inode.
245  */
246 int
247 zfs_inode_alloc(struct super_block *sb, struct inode **ip)
248 {
249         znode_t *zp;
250
251         zp = kmem_cache_alloc(znode_cache, KM_PUSHPAGE);
252         *ip = ZTOI(zp);
253
254         return (0);
255 }
256
257 /*
258  * Called in multiple places when an inode should be destroyed.
259  */
260 void
261 zfs_inode_destroy(struct inode *ip)
262 {
263         znode_t *zp = ITOZ(ip);
264         zfs_sb_t *zsb = ZTOZSB(zp);
265
266         mutex_enter(&zsb->z_znodes_lock);
267         list_remove(&zsb->z_all_znodes, zp);
268         mutex_exit(&zsb->z_znodes_lock);
269
270         if (zp->z_acl_cached) {
271                 zfs_acl_free(zp->z_acl_cached);
272                 zp->z_acl_cached = NULL;
273         }
274
275         kmem_cache_free(znode_cache, zp);
276 }
277
278 static void
279 zfs_inode_set_ops(zfs_sb_t *zsb, struct inode *ip)
280 {
281         uint64_t rdev;
282
283         switch (ip->i_mode & S_IFMT) {
284         case S_IFREG:
285                 ip->i_op = &zpl_inode_operations;
286                 ip->i_fop = &zpl_file_operations;
287                 ip->i_mapping->a_ops = &zpl_address_space_operations;
288                 break;
289
290         case S_IFDIR:
291                 ip->i_op = &zpl_dir_inode_operations;
292                 ip->i_fop = &zpl_dir_file_operations;
293                 ITOZ(ip)->z_zn_prefetch = B_TRUE;
294                 break;
295
296         case S_IFLNK:
297                 ip->i_op = &zpl_symlink_inode_operations;
298                 break;
299
300         case S_IFCHR:
301         case S_IFBLK:
302         case S_IFIFO:
303         case S_IFSOCK:
304                 VERIFY(sa_lookup(ITOZ(ip)->z_sa_hdl, SA_ZPL_RDEV(zsb),
305                     &rdev, sizeof (rdev)) == 0);
306                 init_special_inode(ip, ip->i_mode, rdev);
307                 ip->i_op = &zpl_special_inode_operations;
308                 break;
309
310         default:
311                 printk("ZFS: Invalid mode: 0x%x\n", ip->i_mode);
312                 VERIFY(0);
313         }
314 }
315
316 /*
317  * Construct a znode+inode and initialize.
318  *
319  * This does not do a call to dmu_set_user() that is
320  * up to the caller to do, in case you don't want to
321  * return the znode
322  */
323 static znode_t *
324 zfs_znode_alloc(zfs_sb_t *zsb, dmu_buf_t *db, int blksz,
325     dmu_object_type_t obj_type, uint64_t obj, sa_handle_t *hdl,
326     struct dentry *dentry)
327 {
328         znode_t *zp;
329         struct inode *ip;
330         uint64_t parent;
331         sa_bulk_attr_t bulk[9];
332         int count = 0;
333
334         ASSERT(zsb != NULL);
335
336         ip = new_inode(zsb->z_sb);
337         if (ip == NULL)
338                 return (NULL);
339
340         zp = ITOZ(ip);
341         ASSERT(zp->z_dirlocks == NULL);
342         zp->z_moved = 0;
343         zp->z_sa_hdl = NULL;
344         zp->z_unlinked = 0;
345         zp->z_atime_dirty = 0;
346         zp->z_mapcnt = 0;
347         zp->z_id = db->db_object;
348         zp->z_blksz = blksz;
349         zp->z_seq = 0x7A4653;
350         zp->z_sync_cnt = 0;
351         zp->z_is_zvol = 0;
352
353         zfs_znode_sa_init(zsb, zp, db, obj_type, hdl);
354
355         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zsb), NULL, &zp->z_mode, 8);
356         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zsb), NULL, &zp->z_gen, 8);
357         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zsb), NULL, &zp->z_size, 8);
358         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zsb), NULL, &zp->z_links, 8);
359         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zsb), NULL,
360             &zp->z_pflags, 8);
361         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PARENT(zsb), NULL,
362             &parent, 8);
363         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zsb), NULL,
364             &zp->z_atime, 16);
365         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zsb), NULL, &zp->z_uid, 8);
366         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zsb), NULL, &zp->z_gid, 8);
367
368         if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count) != 0 || zp->z_gen == 0) {
369                 if (hdl == NULL)
370                         sa_handle_destroy(zp->z_sa_hdl);
371
372                 goto error;
373         }
374
375         ip->i_ino = obj;
376         ip->i_mode = zp->z_mode;
377         ip->i_mtime = ip->i_atime = ip->i_ctime = CURRENT_TIME_SEC;
378         zfs_inode_set_ops(zsb, ip);
379
380         if (insert_inode_locked(ip))
381                 goto error;
382
383         if (dentry)
384                 d_instantiate(dentry, ip);
385
386         mutex_enter(&zsb->z_znodes_lock);
387         list_insert_tail(&zsb->z_all_znodes, zp);
388         membar_producer();
389         mutex_exit(&zsb->z_znodes_lock);
390
391         unlock_new_inode(ip);
392         return (zp);
393
394 error:
395         unlock_new_inode(ip);
396         iput(ip);
397         return NULL;
398 }
399
400 /*
401  * Update the embedded inode given the znode.  We should work toward
402  * eliminating this function as soon as possible by removing values
403  * which are duplicated between the znode and inode.  If the generic
404  * inode has the correct field it should be used, and the ZFS code
405  * updated to access the inode.  This can be done incrementally.
406  */
407 void
408 zfs_inode_update(znode_t *zp)
409 {
410         zfs_sb_t        *zsb;
411         struct inode    *ip;
412         uint32_t        blksize;
413         uint64_t        atime[2], mtime[2], ctime[2];
414
415         ASSERT(zp != NULL);
416         zsb = ZTOZSB(zp);
417         ip = ZTOI(zp);
418
419         sa_lookup(zp->z_sa_hdl, SA_ZPL_ATIME(zsb), &atime, 16);
420         sa_lookup(zp->z_sa_hdl, SA_ZPL_MTIME(zsb), &mtime, 16);
421         sa_lookup(zp->z_sa_hdl, SA_ZPL_CTIME(zsb), &ctime, 16);
422
423         spin_lock(&ip->i_lock);
424         ip->i_generation = zp->z_gen;
425         ip->i_uid = zp->z_uid;
426         ip->i_gid = zp->z_gid;
427         ip->i_nlink = zp->z_links;
428         ip->i_mode = zp->z_mode;
429         ip->i_blkbits = SPA_MINBLOCKSHIFT;
430         dmu_object_size_from_db(sa_get_db(zp->z_sa_hdl), &blksize,
431             (u_longlong_t *)&ip->i_blocks);
432
433         ZFS_TIME_DECODE(&ip->i_atime, atime);
434         ZFS_TIME_DECODE(&ip->i_mtime, mtime);
435         ZFS_TIME_DECODE(&ip->i_ctime, ctime);
436
437         i_size_write(ip, zp->z_size);
438         spin_unlock(&ip->i_lock);
439 }
440
441 static uint64_t empty_xattr;
442 static uint64_t pad[4];
443 static zfs_acl_phys_t acl_phys;
444 /*
445  * Create a new DMU object to hold a zfs znode.
446  *
447  *      IN:     dzp     - parent directory for new znode
448  *              vap     - file attributes for new znode
449  *              tx      - dmu transaction id for zap operations
450  *              cr      - credentials of caller
451  *              flag    - flags:
452  *                        IS_ROOT_NODE  - new object will be root
453  *                        IS_XATTR      - new object is an attribute
454  *              bonuslen - length of bonus buffer
455  *              setaclp  - File/Dir initial ACL
456  *              fuidp    - Tracks fuid allocation.
457  *
458  *      OUT:    zpp     - allocated znode
459  *
460  */
461 void
462 zfs_mknode(znode_t *dzp, vattr_t *vap, dmu_tx_t *tx, cred_t *cr,
463     uint_t flag, znode_t **zpp, zfs_acl_ids_t *acl_ids)
464 {
465         uint64_t        crtime[2], atime[2], mtime[2], ctime[2];
466         uint64_t        mode, size, links, parent, pflags;
467         uint64_t        dzp_pflags = 0;
468         uint64_t        rdev = 0;
469         zfs_sb_t        *zsb = ZTOZSB(dzp);
470         dmu_buf_t       *db;
471         timestruc_t     now;
472         uint64_t        gen, obj;
473         int             err;
474         int             bonuslen;
475         sa_handle_t     *sa_hdl;
476         dmu_object_type_t obj_type;
477         sa_bulk_attr_t  *sa_attrs;
478         int             cnt = 0;
479         zfs_acl_locator_cb_t locate = { 0 };
480
481         if (zsb->z_replay) {
482                 obj = vap->va_nodeid;
483                 now = vap->va_ctime;            /* see zfs_replay_create() */
484                 gen = vap->va_nblocks;          /* ditto */
485         } else {
486                 obj = 0;
487                 gethrestime(&now);
488                 gen = dmu_tx_get_txg(tx);
489         }
490
491         obj_type = zsb->z_use_sa ? DMU_OT_SA : DMU_OT_ZNODE;
492         bonuslen = (obj_type == DMU_OT_SA) ?
493             DN_MAX_BONUSLEN : ZFS_OLD_ZNODE_PHYS_SIZE;
494
495         /*
496          * Create a new DMU object.
497          */
498         /*
499          * There's currently no mechanism for pre-reading the blocks that will
500          * be needed to allocate a new object, so we accept the small chance
501          * that there will be an i/o error and we will fail one of the
502          * assertions below.
503          */
504         if (S_ISDIR(vap->va_mode)) {
505                 if (zsb->z_replay) {
506                         err = zap_create_claim_norm(zsb->z_os, obj,
507                             zsb->z_norm, DMU_OT_DIRECTORY_CONTENTS,
508                             obj_type, bonuslen, tx);
509                         ASSERT3U(err, ==, 0);
510                 } else {
511                         obj = zap_create_norm(zsb->z_os,
512                             zsb->z_norm, DMU_OT_DIRECTORY_CONTENTS,
513                             obj_type, bonuslen, tx);
514                 }
515         } else {
516                 if (zsb->z_replay) {
517                         err = dmu_object_claim(zsb->z_os, obj,
518                             DMU_OT_PLAIN_FILE_CONTENTS, 0,
519                             obj_type, bonuslen, tx);
520                         ASSERT3U(err, ==, 0);
521                 } else {
522                         obj = dmu_object_alloc(zsb->z_os,
523                             DMU_OT_PLAIN_FILE_CONTENTS, 0,
524                             obj_type, bonuslen, tx);
525                 }
526         }
527
528         ZFS_OBJ_HOLD_ENTER(zsb, obj);
529         VERIFY(0 == sa_buf_hold(zsb->z_os, obj, NULL, &db));
530
531         /*
532          * If this is the root, fix up the half-initialized parent pointer
533          * to reference the just-allocated physical data area.
534          */
535         if (flag & IS_ROOT_NODE) {
536                 dzp->z_id = obj;
537         } else {
538                 dzp_pflags = dzp->z_pflags;
539         }
540
541         /*
542          * If parent is an xattr, so am I.
543          */
544         if (dzp_pflags & ZFS_XATTR) {
545                 flag |= IS_XATTR;
546         }
547
548         if (zsb->z_use_fuids)
549                 pflags = ZFS_ARCHIVE | ZFS_AV_MODIFIED;
550         else
551                 pflags = 0;
552
553         if (S_ISDIR(vap->va_mode)) {
554                 size = 2;               /* contents ("." and "..") */
555                 links = (flag & (IS_ROOT_NODE | IS_XATTR)) ? 2 : 1;
556         } else {
557                 size = links = 0;
558         }
559
560         if (S_ISBLK(vap->va_mode)  || S_ISCHR(vap->va_mode) ||
561             S_ISFIFO(vap->va_mode) || S_ISSOCK(vap->va_mode))
562                 rdev = vap->va_rdev;
563
564         parent = dzp->z_id;
565         mode = acl_ids->z_mode;
566         if (flag & IS_XATTR)
567                 pflags |= ZFS_XATTR;
568
569         /*
570          * No execs denied will be deterimed when zfs_mode_compute() is called.
571          */
572         pflags |= acl_ids->z_aclp->z_hints &
573             (ZFS_ACL_TRIVIAL|ZFS_INHERIT_ACE|ZFS_ACL_AUTO_INHERIT|
574             ZFS_ACL_DEFAULTED|ZFS_ACL_PROTECTED);
575
576         ZFS_TIME_ENCODE(&now, crtime);
577         ZFS_TIME_ENCODE(&now, ctime);
578
579         if (vap->va_mask & ATTR_ATIME) {
580                 ZFS_TIME_ENCODE(&vap->va_atime, atime);
581         } else {
582                 ZFS_TIME_ENCODE(&now, atime);
583         }
584
585         if (vap->va_mask & ATTR_MTIME) {
586                 ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
587         } else {
588                 ZFS_TIME_ENCODE(&now, mtime);
589         }
590
591         /* Now add in all of the "SA" attributes */
592         VERIFY(0 == sa_handle_get_from_db(zsb->z_os, db, NULL, SA_HDL_SHARED,
593             &sa_hdl));
594
595         /*
596          * Setup the array of attributes to be replaced/set on the new file
597          *
598          * order for  DMU_OT_ZNODE is critical since it needs to be constructed
599          * in the old znode_phys_t format.  Don't change this ordering
600          */
601         sa_attrs = kmem_alloc(sizeof(sa_bulk_attr_t) * ZPL_END, KM_SLEEP);
602
603         if (obj_type == DMU_OT_ZNODE) {
604                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ATIME(zsb),
605                     NULL, &atime, 16);
606                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MTIME(zsb),
607                     NULL, &mtime, 16);
608                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CTIME(zsb),
609                     NULL, &ctime, 16);
610                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CRTIME(zsb),
611                     NULL, &crtime, 16);
612                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GEN(zsb),
613                     NULL, &gen, 8);
614                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MODE(zsb),
615                     NULL, &mode, 8);
616                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_SIZE(zsb),
617                     NULL, &size, 8);
618                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PARENT(zsb),
619                     NULL, &parent, 8);
620         } else {
621                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MODE(zsb),
622                     NULL, &mode, 8);
623                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_SIZE(zsb),
624                     NULL, &size, 8);
625                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GEN(zsb),
626                     NULL, &gen, 8);
627                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_UID(zsb),
628                     NULL, &acl_ids->z_fuid, 8);
629                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GID(zsb),
630                     NULL, &acl_ids->z_fgid, 8);
631                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PARENT(zsb),
632                     NULL, &parent, 8);
633                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_FLAGS(zsb),
634                     NULL, &pflags, 8);
635                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ATIME(zsb),
636                     NULL, &atime, 16);
637                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MTIME(zsb),
638                     NULL, &mtime, 16);
639                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CTIME(zsb),
640                     NULL, &ctime, 16);
641                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CRTIME(zsb),
642                     NULL, &crtime, 16);
643         }
644
645         SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_LINKS(zsb), NULL, &links, 8);
646
647         if (obj_type == DMU_OT_ZNODE) {
648                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_XATTR(zsb), NULL,
649                     &empty_xattr, 8);
650         }
651         if (obj_type == DMU_OT_ZNODE ||
652             (S_ISBLK(vap->va_mode)  || S_ISCHR(vap->va_mode) ||
653              S_ISFIFO(vap->va_mode) || S_ISSOCK(vap->va_mode))) {
654                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_RDEV(zsb),
655                     NULL, &rdev, 8);
656         }
657         if (obj_type == DMU_OT_ZNODE) {
658                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_FLAGS(zsb),
659                     NULL, &pflags, 8);
660                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_UID(zsb), NULL,
661                     &acl_ids->z_fuid, 8);
662                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GID(zsb), NULL,
663                     &acl_ids->z_fgid, 8);
664                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PAD(zsb), NULL, pad,
665                     sizeof (uint64_t) * 4);
666                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ZNODE_ACL(zsb), NULL,
667                     &acl_phys, sizeof (zfs_acl_phys_t));
668         } else if (acl_ids->z_aclp->z_version >= ZFS_ACL_VERSION_FUID) {
669                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_DACL_COUNT(zsb), NULL,
670                     &acl_ids->z_aclp->z_acl_count, 8);
671                 locate.cb_aclp = acl_ids->z_aclp;
672                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_DACL_ACES(zsb),
673                     zfs_acl_data_locator, &locate,
674                     acl_ids->z_aclp->z_acl_bytes);
675                 mode = zfs_mode_compute(mode, acl_ids->z_aclp, &pflags,
676                     acl_ids->z_fuid, acl_ids->z_fgid);
677         }
678
679         VERIFY(sa_replace_all_by_template(sa_hdl, sa_attrs, cnt, tx) == 0);
680
681         if (!(flag & IS_ROOT_NODE)) {
682                 *zpp = zfs_znode_alloc(zsb, db, 0, obj_type, obj, sa_hdl,
683                     vap->va_dentry);
684                 ASSERT(*zpp != NULL);
685                 ASSERT(dzp != NULL);
686                 err = zpl_xattr_security_init(ZTOI(*zpp), ZTOI(dzp));
687                 ASSERT3S(err, ==, 0);
688         } else {
689                 /*
690                  * If we are creating the root node, the "parent" we
691                  * passed in is the znode for the root.
692                  */
693                 *zpp = dzp;
694
695                 (*zpp)->z_sa_hdl = sa_hdl;
696         }
697
698         (*zpp)->z_pflags = pflags;
699         (*zpp)->z_mode = mode;
700
701         if (obj_type == DMU_OT_ZNODE ||
702             acl_ids->z_aclp->z_version < ZFS_ACL_VERSION_FUID) {
703                 err = zfs_aclset_common(*zpp, acl_ids->z_aclp, cr, tx);
704                 ASSERT3S(err, ==, 0);
705         }
706         kmem_free(sa_attrs, sizeof(sa_bulk_attr_t) * ZPL_END);
707         ZFS_OBJ_HOLD_EXIT(zsb, obj);
708 }
709
710 /*
711  * zfs_xvattr_set only updates the in-core attributes
712  * it is assumed the caller will be doing an sa_bulk_update
713  * to push the changes out
714  */
715 void
716 zfs_xvattr_set(znode_t *zp, xvattr_t *xvap, dmu_tx_t *tx)
717 {
718         xoptattr_t *xoap;
719
720         xoap = xva_getxoptattr(xvap);
721         ASSERT(xoap);
722
723         if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
724                 uint64_t times[2];
725                 ZFS_TIME_ENCODE(&xoap->xoa_createtime, times);
726                 (void) sa_update(zp->z_sa_hdl, SA_ZPL_CRTIME(ZTOZSB(zp)),
727                     &times, sizeof (times), tx);
728                 XVA_SET_RTN(xvap, XAT_CREATETIME);
729         }
730         if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
731                 ZFS_ATTR_SET(zp, ZFS_READONLY, xoap->xoa_readonly,
732                     zp->z_pflags, tx);
733                 XVA_SET_RTN(xvap, XAT_READONLY);
734         }
735         if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
736                 ZFS_ATTR_SET(zp, ZFS_HIDDEN, xoap->xoa_hidden,
737                     zp->z_pflags, tx);
738                 XVA_SET_RTN(xvap, XAT_HIDDEN);
739         }
740         if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
741                 ZFS_ATTR_SET(zp, ZFS_SYSTEM, xoap->xoa_system,
742                     zp->z_pflags, tx);
743                 XVA_SET_RTN(xvap, XAT_SYSTEM);
744         }
745         if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
746                 ZFS_ATTR_SET(zp, ZFS_ARCHIVE, xoap->xoa_archive,
747                     zp->z_pflags, tx);
748                 XVA_SET_RTN(xvap, XAT_ARCHIVE);
749         }
750         if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
751                 ZFS_ATTR_SET(zp, ZFS_IMMUTABLE, xoap->xoa_immutable,
752                     zp->z_pflags, tx);
753                 XVA_SET_RTN(xvap, XAT_IMMUTABLE);
754         }
755         if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
756                 ZFS_ATTR_SET(zp, ZFS_NOUNLINK, xoap->xoa_nounlink,
757                     zp->z_pflags, tx);
758                 XVA_SET_RTN(xvap, XAT_NOUNLINK);
759         }
760         if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
761                 ZFS_ATTR_SET(zp, ZFS_APPENDONLY, xoap->xoa_appendonly,
762                     zp->z_pflags, tx);
763                 XVA_SET_RTN(xvap, XAT_APPENDONLY);
764         }
765         if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
766                 ZFS_ATTR_SET(zp, ZFS_NODUMP, xoap->xoa_nodump,
767                     zp->z_pflags, tx);
768                 XVA_SET_RTN(xvap, XAT_NODUMP);
769         }
770         if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
771                 ZFS_ATTR_SET(zp, ZFS_OPAQUE, xoap->xoa_opaque,
772                     zp->z_pflags, tx);
773                 XVA_SET_RTN(xvap, XAT_OPAQUE);
774         }
775         if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
776                 ZFS_ATTR_SET(zp, ZFS_AV_QUARANTINED,
777                     xoap->xoa_av_quarantined, zp->z_pflags, tx);
778                 XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
779         }
780         if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
781                 ZFS_ATTR_SET(zp, ZFS_AV_MODIFIED, xoap->xoa_av_modified,
782                     zp->z_pflags, tx);
783                 XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
784         }
785         if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
786                 zfs_sa_set_scanstamp(zp, xvap, tx);
787                 XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
788         }
789         if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
790                 ZFS_ATTR_SET(zp, ZFS_REPARSE, xoap->xoa_reparse,
791                     zp->z_pflags, tx);
792                 XVA_SET_RTN(xvap, XAT_REPARSE);
793         }
794         if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
795                 ZFS_ATTR_SET(zp, ZFS_OFFLINE, xoap->xoa_offline,
796                     zp->z_pflags, tx);
797                 XVA_SET_RTN(xvap, XAT_OFFLINE);
798         }
799         if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
800                 ZFS_ATTR_SET(zp, ZFS_SPARSE, xoap->xoa_sparse,
801                     zp->z_pflags, tx);
802                 XVA_SET_RTN(xvap, XAT_SPARSE);
803         }
804 }
805
806 int
807 zfs_zget(zfs_sb_t *zsb, uint64_t obj_num, znode_t **zpp)
808 {
809         dmu_object_info_t doi;
810         dmu_buf_t       *db;
811         znode_t         *zp;
812         int err;
813         sa_handle_t     *hdl;
814         struct inode    *ip;
815
816         *zpp = NULL;
817
818 again:
819         ip = ilookup(zsb->z_sb, obj_num);
820
821         ZFS_OBJ_HOLD_ENTER(zsb, obj_num);
822
823         err = sa_buf_hold(zsb->z_os, obj_num, NULL, &db);
824         if (err) {
825                 ZFS_OBJ_HOLD_EXIT(zsb, obj_num);
826                 iput(ip);
827                 return (err);
828         }
829
830         dmu_object_info_from_db(db, &doi);
831         if (doi.doi_bonus_type != DMU_OT_SA &&
832             (doi.doi_bonus_type != DMU_OT_ZNODE ||
833             (doi.doi_bonus_type == DMU_OT_ZNODE &&
834             doi.doi_bonus_size < sizeof (znode_phys_t)))) {
835                 sa_buf_rele(db, NULL);
836                 ZFS_OBJ_HOLD_EXIT(zsb, obj_num);
837                 iput(ip);
838                 return (EINVAL);
839         }
840
841         hdl = dmu_buf_get_user(db);
842         if (hdl != NULL) {
843                 if (ip == NULL) {
844                         /*
845                          * ilookup returned NULL, which means
846                          * the znode is dying - but the SA handle isn't
847                          * quite dead yet, we need to drop any locks
848                          * we're holding, re-schedule the task and try again.
849                          */
850                         sa_buf_rele(db, NULL);
851                         ZFS_OBJ_HOLD_EXIT(zsb, obj_num);
852
853                         schedule();
854                         goto again;
855                 }
856
857                 zp = sa_get_userdata(hdl);
858
859                 /*
860                  * Since "SA" does immediate eviction we
861                  * should never find a sa handle that doesn't
862                  * know about the znode.
863                  */
864
865                 ASSERT3P(zp, !=, NULL);
866
867                 mutex_enter(&zp->z_lock);
868                 ASSERT3U(zp->z_id, ==, obj_num);
869                 if (zp->z_unlinked) {
870                         err = ENOENT;
871                 } else {
872                         igrab(ZTOI(zp));
873                         *zpp = zp;
874                         err = 0;
875                 }
876                 sa_buf_rele(db, NULL);
877                 mutex_exit(&zp->z_lock);
878                 ZFS_OBJ_HOLD_EXIT(zsb, obj_num);
879                 iput(ip);
880                 return (err);
881         }
882
883         ASSERT3P(ip, ==, NULL);
884
885         /*
886          * Not found create new znode/vnode but only if file exists.
887          *
888          * There is a small window where zfs_vget() could
889          * find this object while a file create is still in
890          * progress.  This is checked for in zfs_znode_alloc()
891          *
892          * if zfs_znode_alloc() fails it will drop the hold on the
893          * bonus buffer.
894          */
895         zp = zfs_znode_alloc(zsb, db, doi.doi_data_block_size,
896             doi.doi_bonus_type, obj_num, NULL, NULL);
897         if (zp == NULL) {
898                 err = ENOENT;
899         } else {
900                 *zpp = zp;
901         }
902         ZFS_OBJ_HOLD_EXIT(zsb, obj_num);
903         return (err);
904 }
905
906 int
907 zfs_rezget(znode_t *zp)
908 {
909         zfs_sb_t *zsb = ZTOZSB(zp);
910         dmu_object_info_t doi;
911         dmu_buf_t *db;
912         uint64_t obj_num = zp->z_id;
913         uint64_t mode;
914         sa_bulk_attr_t bulk[8];
915         int err;
916         int count = 0;
917         uint64_t gen;
918
919         ZFS_OBJ_HOLD_ENTER(zsb, obj_num);
920
921         mutex_enter(&zp->z_acl_lock);
922         if (zp->z_acl_cached) {
923                 zfs_acl_free(zp->z_acl_cached);
924                 zp->z_acl_cached = NULL;
925         }
926
927         mutex_exit(&zp->z_acl_lock);
928         ASSERT(zp->z_sa_hdl == NULL);
929         err = sa_buf_hold(zsb->z_os, obj_num, NULL, &db);
930         if (err) {
931                 ZFS_OBJ_HOLD_EXIT(zsb, obj_num);
932                 return (err);
933         }
934
935         dmu_object_info_from_db(db, &doi);
936         if (doi.doi_bonus_type != DMU_OT_SA &&
937             (doi.doi_bonus_type != DMU_OT_ZNODE ||
938             (doi.doi_bonus_type == DMU_OT_ZNODE &&
939             doi.doi_bonus_size < sizeof (znode_phys_t)))) {
940                 sa_buf_rele(db, NULL);
941                 ZFS_OBJ_HOLD_EXIT(zsb, obj_num);
942                 return (EINVAL);
943         }
944
945         zfs_znode_sa_init(zsb, zp, db, doi.doi_bonus_type, NULL);
946
947         /* reload cached values */
948         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zsb), NULL,
949             &gen, sizeof (gen));
950         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zsb), NULL,
951             &zp->z_size, sizeof (zp->z_size));
952         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zsb), NULL,
953             &zp->z_links, sizeof (zp->z_links));
954         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zsb), NULL,
955             &zp->z_pflags, sizeof (zp->z_pflags));
956         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zsb), NULL,
957             &zp->z_atime, sizeof (zp->z_atime));
958         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zsb), NULL,
959             &zp->z_uid, sizeof (zp->z_uid));
960         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zsb), NULL,
961             &zp->z_gid, sizeof (zp->z_gid));
962         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zsb), NULL,
963             &mode, sizeof (mode));
964
965         if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) {
966                 zfs_znode_dmu_fini(zp);
967                 ZFS_OBJ_HOLD_EXIT(zsb, obj_num);
968                 return (EIO);
969         }
970
971         zp->z_mode = mode;
972
973         if (gen != zp->z_gen) {
974                 zfs_znode_dmu_fini(zp);
975                 ZFS_OBJ_HOLD_EXIT(zsb, obj_num);
976                 return (EIO);
977         }
978
979         zp->z_unlinked = (zp->z_links == 0);
980         zp->z_blksz = doi.doi_data_block_size;
981
982         ZFS_OBJ_HOLD_EXIT(zsb, obj_num);
983
984         return (0);
985 }
986
987 void
988 zfs_znode_delete(znode_t *zp, dmu_tx_t *tx)
989 {
990         zfs_sb_t *zsb = ZTOZSB(zp);
991         objset_t *os = zsb->z_os;
992         uint64_t obj = zp->z_id;
993         uint64_t acl_obj = zfs_external_acl(zp);
994
995         ZFS_OBJ_HOLD_ENTER(zsb, obj);
996         if (acl_obj) {
997                 VERIFY(!zp->z_is_sa);
998                 VERIFY(0 == dmu_object_free(os, acl_obj, tx));
999         }
1000         VERIFY(0 == dmu_object_free(os, obj, tx));
1001         zfs_znode_dmu_fini(zp);
1002         ZFS_OBJ_HOLD_EXIT(zsb, obj);
1003 }
1004
1005 void
1006 zfs_zinactive(znode_t *zp)
1007 {
1008         zfs_sb_t *zsb = ZTOZSB(zp);
1009         uint64_t z_id = zp->z_id;
1010         boolean_t drop_mutex = 0;
1011
1012         ASSERT(zp->z_sa_hdl);
1013
1014         /*
1015          * Don't allow a zfs_zget() while were trying to release this znode.
1016          *
1017          * Linux allows direct memory reclaim which means that any KM_SLEEP
1018          * allocation may trigger inode eviction.  This can lead to a deadlock
1019          * through the ->shrink_icache_memory()->evict()->zfs_inactive()->
1020          * zfs_zinactive() call path.  To avoid this deadlock the process
1021          * must not reacquire the mutex when it is already holding it.
1022          */
1023         if (!ZFS_OBJ_HOLD_OWNED(zsb, z_id)) {
1024                 ZFS_OBJ_HOLD_ENTER(zsb, z_id);
1025                 drop_mutex = 1;
1026         }
1027
1028         mutex_enter(&zp->z_lock);
1029
1030         /*
1031          * If this was the last reference to a file with no links,
1032          * remove the file from the file system.
1033          */
1034         if (zp->z_unlinked) {
1035                 mutex_exit(&zp->z_lock);
1036
1037                 if (drop_mutex)
1038                         ZFS_OBJ_HOLD_EXIT(zsb, z_id);
1039
1040                 zfs_rmnode(zp);
1041                 return;
1042         }
1043
1044         mutex_exit(&zp->z_lock);
1045         zfs_znode_dmu_fini(zp);
1046
1047         if (drop_mutex)
1048                 ZFS_OBJ_HOLD_EXIT(zsb, z_id);
1049 }
1050
1051 void
1052 zfs_tstamp_update_setup(znode_t *zp, uint_t flag, uint64_t mtime[2],
1053     uint64_t ctime[2], boolean_t have_tx)
1054 {
1055         timestruc_t     now;
1056
1057         gethrestime(&now);
1058
1059         if (have_tx) {  /* will sa_bulk_update happen really soon? */
1060                 zp->z_atime_dirty = 0;
1061                 zp->z_seq++;
1062         } else {
1063                 zp->z_atime_dirty = 1;
1064         }
1065
1066         if (flag & ATTR_ATIME) {
1067                 ZFS_TIME_ENCODE(&now, zp->z_atime);
1068         }
1069
1070         if (flag & ATTR_MTIME) {
1071                 ZFS_TIME_ENCODE(&now, mtime);
1072                 if (ZTOZSB(zp)->z_use_fuids) {
1073                         zp->z_pflags |= (ZFS_ARCHIVE |
1074                             ZFS_AV_MODIFIED);
1075                 }
1076         }
1077
1078         if (flag & ATTR_CTIME) {
1079                 ZFS_TIME_ENCODE(&now, ctime);
1080                 if (ZTOZSB(zp)->z_use_fuids)
1081                         zp->z_pflags |= ZFS_ARCHIVE;
1082         }
1083 }
1084
1085 /*
1086  * Grow the block size for a file.
1087  *
1088  *      IN:     zp      - znode of file to free data in.
1089  *              size    - requested block size
1090  *              tx      - open transaction.
1091  *
1092  * NOTE: this function assumes that the znode is write locked.
1093  */
1094 void
1095 zfs_grow_blocksize(znode_t *zp, uint64_t size, dmu_tx_t *tx)
1096 {
1097         int             error;
1098         u_longlong_t    dummy;
1099
1100         if (size <= zp->z_blksz)
1101                 return;
1102         /*
1103          * If the file size is already greater than the current blocksize,
1104          * we will not grow.  If there is more than one block in a file,
1105          * the blocksize cannot change.
1106          */
1107         if (zp->z_blksz && zp->z_size > zp->z_blksz)
1108                 return;
1109
1110         error = dmu_object_set_blocksize(ZTOZSB(zp)->z_os, zp->z_id,
1111             size, 0, tx);
1112
1113         if (error == ENOTSUP)
1114                 return;
1115         ASSERT3U(error, ==, 0);
1116
1117         /* What blocksize did we actually get? */
1118         dmu_object_size_from_db(sa_get_db(zp->z_sa_hdl), &zp->z_blksz, &dummy);
1119 }
1120
1121 #ifdef HAVE_MMAP
1122 /*
1123  * This is a dummy interface used when pvn_vplist_dirty() should *not*
1124  * be calling back into the fs for a putpage().  E.g.: when truncating
1125  * a file, the pages being "thrown away* don't need to be written out.
1126  */
1127 /* ARGSUSED */
1128 static int
1129 zfs_no_putpage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
1130     int flags, cred_t *cr)
1131 {
1132         ASSERT(0);
1133         return (0);
1134 }
1135 #endif /* HAVE_MMAP */
1136
1137 /*
1138  * Increase the file length
1139  *
1140  *      IN:     zp      - znode of file to free data in.
1141  *              end     - new end-of-file
1142  *
1143  *      RETURN: 0 if success
1144  *              error code if failure
1145  */
1146 static int
1147 zfs_extend(znode_t *zp, uint64_t end)
1148 {
1149         zfs_sb_t *zsb = ZTOZSB(zp);
1150         dmu_tx_t *tx;
1151         rl_t *rl;
1152         uint64_t newblksz;
1153         int error;
1154
1155         /*
1156          * We will change zp_size, lock the whole file.
1157          */
1158         rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1159
1160         /*
1161          * Nothing to do if file already at desired length.
1162          */
1163         if (end <= zp->z_size) {
1164                 zfs_range_unlock(rl);
1165                 return (0);
1166         }
1167 top:
1168         tx = dmu_tx_create(zsb->z_os);
1169         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1170         zfs_sa_upgrade_txholds(tx, zp);
1171         if (end > zp->z_blksz &&
1172             (!ISP2(zp->z_blksz) || zp->z_blksz < zsb->z_max_blksz)) {
1173                 /*
1174                  * We are growing the file past the current block size.
1175                  */
1176                 if (zp->z_blksz > ZTOZSB(zp)->z_max_blksz) {
1177                         ASSERT(!ISP2(zp->z_blksz));
1178                         newblksz = MIN(end, SPA_MAXBLOCKSIZE);
1179                 } else {
1180                         newblksz = MIN(end, ZTOZSB(zp)->z_max_blksz);
1181                 }
1182                 dmu_tx_hold_write(tx, zp->z_id, 0, newblksz);
1183         } else {
1184                 newblksz = 0;
1185         }
1186
1187         error = dmu_tx_assign(tx, TXG_NOWAIT);
1188         if (error) {
1189                 if (error == ERESTART) {
1190                         dmu_tx_wait(tx);
1191                         dmu_tx_abort(tx);
1192                         goto top;
1193                 }
1194                 dmu_tx_abort(tx);
1195                 zfs_range_unlock(rl);
1196                 return (error);
1197         }
1198
1199         if (newblksz)
1200                 zfs_grow_blocksize(zp, newblksz, tx);
1201
1202         zp->z_size = end;
1203
1204         VERIFY(0 == sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(ZTOZSB(zp)),
1205             &zp->z_size, sizeof (zp->z_size), tx));
1206
1207         zfs_range_unlock(rl);
1208
1209         dmu_tx_commit(tx);
1210
1211         return (0);
1212 }
1213
1214 /*
1215  * Free space in a file.
1216  *
1217  *      IN:     zp      - znode of file to free data in.
1218  *              off     - start of section to free.
1219  *              len     - length of section to free.
1220  *
1221  *      RETURN: 0 if success
1222  *              error code if failure
1223  */
1224 static int
1225 zfs_free_range(znode_t *zp, uint64_t off, uint64_t len)
1226 {
1227         zfs_sb_t *zsb = ZTOZSB(zp);
1228         rl_t *rl;
1229         int error;
1230
1231         /*
1232          * Lock the range being freed.
1233          */
1234         rl = zfs_range_lock(zp, off, len, RL_WRITER);
1235
1236         /*
1237          * Nothing to do if file already at desired length.
1238          */
1239         if (off >= zp->z_size) {
1240                 zfs_range_unlock(rl);
1241                 return (0);
1242         }
1243
1244         if (off + len > zp->z_size)
1245                 len = zp->z_size - off;
1246
1247         error = dmu_free_long_range(zsb->z_os, zp->z_id, off, len);
1248
1249         zfs_range_unlock(rl);
1250
1251         return (error);
1252 }
1253
1254 /*
1255  * Truncate a file
1256  *
1257  *      IN:     zp      - znode of file to free data in.
1258  *              end     - new end-of-file.
1259  *
1260  *      RETURN: 0 if success
1261  *              error code if failure
1262  */
1263 static int
1264 zfs_trunc(znode_t *zp, uint64_t end)
1265 {
1266         zfs_sb_t *zsb = ZTOZSB(zp);
1267         dmu_tx_t *tx;
1268         rl_t *rl;
1269         int error;
1270         sa_bulk_attr_t bulk[2];
1271         int count = 0;
1272
1273         /*
1274          * We will change zp_size, lock the whole file.
1275          */
1276         rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1277
1278         /*
1279          * Nothing to do if file already at desired length.
1280          */
1281         if (end >= zp->z_size) {
1282                 zfs_range_unlock(rl);
1283                 return (0);
1284         }
1285
1286         error = dmu_free_long_range(zsb->z_os, zp->z_id, end,  -1);
1287         if (error) {
1288                 zfs_range_unlock(rl);
1289                 return (error);
1290         }
1291 top:
1292         tx = dmu_tx_create(zsb->z_os);
1293         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1294         zfs_sa_upgrade_txholds(tx, zp);
1295         error = dmu_tx_assign(tx, TXG_NOWAIT);
1296         if (error) {
1297                 if (error == ERESTART) {
1298                         dmu_tx_wait(tx);
1299                         dmu_tx_abort(tx);
1300                         goto top;
1301                 }
1302                 dmu_tx_abort(tx);
1303                 zfs_range_unlock(rl);
1304                 return (error);
1305         }
1306
1307         zp->z_size = end;
1308         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zsb),
1309             NULL, &zp->z_size, sizeof (zp->z_size));
1310
1311         if (end == 0) {
1312                 zp->z_pflags &= ~ZFS_SPARSE;
1313                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zsb),
1314                     NULL, &zp->z_pflags, 8);
1315         }
1316         VERIFY(sa_bulk_update(zp->z_sa_hdl, bulk, count, tx) == 0);
1317
1318         dmu_tx_commit(tx);
1319
1320         zfs_range_unlock(rl);
1321
1322         return (0);
1323 }
1324
1325 /*
1326  * Free space in a file
1327  *
1328  *      IN:     zp      - znode of file to free data in.
1329  *              off     - start of range
1330  *              len     - end of range (0 => EOF)
1331  *              flag    - current file open mode flags.
1332  *              log     - TRUE if this action should be logged
1333  *
1334  *      RETURN: 0 if success
1335  *              error code if failure
1336  */
1337 int
1338 zfs_freesp(znode_t *zp, uint64_t off, uint64_t len, int flag, boolean_t log)
1339 {
1340 #ifdef HAVE_MANDLOCKS
1341         struct inode *ip = ZTOI(zp);
1342 #endif /* HAVE_MANDLOCKS */
1343         dmu_tx_t *tx;
1344         zfs_sb_t *zsb = ZTOZSB(zp);
1345         zilog_t *zilog = zsb->z_log;
1346         uint64_t mode;
1347         uint64_t mtime[2], ctime[2];
1348         sa_bulk_attr_t bulk[3];
1349         int count = 0;
1350         int error;
1351
1352         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_MODE(zsb), &mode,
1353             sizeof (mode))) != 0)
1354                 return (error);
1355
1356         if (off > zp->z_size) {
1357                 error =  zfs_extend(zp, off+len);
1358                 if (error == 0 && log)
1359                         goto log;
1360                 else
1361                         return (error);
1362         }
1363
1364 #ifdef HAVE_MANDLOCKS
1365         /*
1366          * Check for any locks in the region to be freed.
1367          */
1368
1369         if (MANDLOCK(ip, (mode_t)mode)) {
1370                 uint64_t length = (len ? len : zp->z_size - off);
1371                 if (error = chklock(ip, FWRITE, off, length, flag, NULL))
1372                         return (error);
1373         }
1374 #endif /* HAVE_MANDLOCKS */
1375
1376         if (len == 0) {
1377                 error = zfs_trunc(zp, off);
1378         } else {
1379                 if ((error = zfs_free_range(zp, off, len)) == 0 &&
1380                     off + len > zp->z_size)
1381                         error = zfs_extend(zp, off+len);
1382         }
1383         if (error || !log)
1384                 return (error);
1385 log:
1386         tx = dmu_tx_create(zsb->z_os);
1387         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1388         zfs_sa_upgrade_txholds(tx, zp);
1389         error = dmu_tx_assign(tx, TXG_NOWAIT);
1390         if (error) {
1391                 if (error == ERESTART) {
1392                         dmu_tx_wait(tx);
1393                         dmu_tx_abort(tx);
1394                         goto log;
1395                 }
1396                 dmu_tx_abort(tx);
1397                 return (error);
1398         }
1399
1400         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zsb), NULL, mtime, 16);
1401         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zsb), NULL, ctime, 16);
1402         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zsb),
1403             NULL, &zp->z_pflags, 8);
1404         zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime, B_TRUE);
1405         error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1406         ASSERT(error == 0);
1407
1408         zfs_log_truncate(zilog, tx, TX_TRUNCATE, zp, off, len);
1409
1410         dmu_tx_commit(tx);
1411         zfs_inode_update(zp);
1412         return (0);
1413 }
1414
1415 void
1416 zfs_create_fs(objset_t *os, cred_t *cr, nvlist_t *zplprops, dmu_tx_t *tx)
1417 {
1418         uint64_t        moid, obj, sa_obj, version;
1419         uint64_t        norm = 0;
1420         nvpair_t        *elem;
1421         int             error;
1422         timestruc_t     now;
1423         dmu_buf_t       *db;
1424         znode_phys_t    *pzp;
1425
1426         /*
1427          * First attempt to create master node.
1428          */
1429         /*
1430          * In an empty objset, there are no blocks to read and thus
1431          * there can be no i/o errors (which we assert below).
1432          */
1433         moid = MASTER_NODE_OBJ;
1434         error = zap_create_claim(os, moid, DMU_OT_MASTER_NODE,
1435             DMU_OT_NONE, 0, tx);
1436         ASSERT(error == 0);
1437
1438         /*
1439          * Set starting attributes.
1440          */
1441         version = zfs_zpl_version_map(spa_version(dmu_objset_spa(os)));
1442         elem = NULL;
1443         while ((elem = nvlist_next_nvpair(zplprops, elem)) != NULL) {
1444                 /* For the moment we expect all zpl props to be uint64_ts */
1445                 uint64_t val;
1446                 char *name;
1447
1448                 ASSERT(nvpair_type(elem) == DATA_TYPE_UINT64);
1449                 VERIFY(nvpair_value_uint64(elem, &val) == 0);
1450                 name = nvpair_name(elem);
1451                 if (strcmp(name, zfs_prop_to_name(ZFS_PROP_VERSION)) == 0) {
1452                         if (val < version)
1453                                 version = val;
1454                 } else {
1455                         error = zap_update(os, moid, name, 8, 1, &val, tx);
1456                 }
1457                 ASSERT(error == 0);
1458                 if (strcmp(name, zfs_prop_to_name(ZFS_PROP_NORMALIZE)) == 0)
1459                         norm = val;
1460         }
1461         ASSERT(version != 0);
1462         error = zap_update(os, moid, ZPL_VERSION_STR, 8, 1, &version, tx);
1463
1464         /*
1465          * Create zap object used for SA attribute registration
1466          */
1467
1468         if (version >= ZPL_VERSION_SA) {
1469                 sa_obj = zap_create(os, DMU_OT_SA_MASTER_NODE,
1470                     DMU_OT_NONE, 0, tx);
1471                 error = zap_add(os, moid, ZFS_SA_ATTRS, 8, 1, &sa_obj, tx);
1472                 ASSERT(error == 0);
1473         } else {
1474                 sa_obj = 0;
1475         }
1476         /*
1477          * Create a delete queue.
1478          */
1479         obj = zap_create(os, DMU_OT_UNLINKED_SET, DMU_OT_NONE, 0, tx);
1480
1481         error = zap_add(os, moid, ZFS_UNLINKED_SET, 8, 1, &obj, tx);
1482         ASSERT(error == 0);
1483
1484         /*
1485          * Create root znode with code free of VFS dependencies.  This
1486          * is important because without a registered filesystem and super
1487          * block all the required VFS hooks will be missing.  The critical
1488          * thing is to just crete the required root znode.
1489          */
1490         obj = zap_create_norm(os, norm, DMU_OT_DIRECTORY_CONTENTS,
1491                               DMU_OT_ZNODE, sizeof (znode_phys_t), tx);
1492
1493         VERIFY(0 == dmu_bonus_hold(os, obj, FTAG, &db));
1494         dmu_buf_will_dirty(db, tx);
1495
1496         /*
1497          * Initialize the znode physical data to zero.
1498          */
1499         ASSERT(db->db_size >= sizeof (znode_phys_t));
1500         bzero(db->db_data, db->db_size);
1501         pzp = db->db_data;
1502
1503         if (USE_FUIDS(version, os))
1504                 pzp->zp_flags = ZFS_ARCHIVE | ZFS_AV_MODIFIED;
1505
1506         pzp->zp_size = 2; /* "." and ".." */
1507         pzp->zp_links = 2;
1508         pzp->zp_parent = obj;
1509         pzp->zp_gen = dmu_tx_get_txg(tx);
1510         pzp->zp_mode = S_IFDIR | 0755;
1511         pzp->zp_flags = ZFS_ACL_TRIVIAL;
1512
1513         gethrestime(&now);
1514
1515         ZFS_TIME_ENCODE(&now, pzp->zp_crtime);
1516         ZFS_TIME_ENCODE(&now, pzp->zp_ctime);
1517         ZFS_TIME_ENCODE(&now, pzp->zp_atime);
1518         ZFS_TIME_ENCODE(&now, pzp->zp_mtime);
1519
1520         error = zap_add(os, moid, ZFS_ROOT_OBJ, 8, 1, &obj, tx);
1521         ASSERT(error == 0);
1522
1523         dmu_buf_rele(db, FTAG);
1524 }
1525
1526 #endif /* _KERNEL */
1527
1528 static int
1529 zfs_sa_setup(objset_t *osp, sa_attr_type_t **sa_table)
1530 {
1531         uint64_t sa_obj = 0;
1532         int error;
1533
1534         error = zap_lookup(osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS, 8, 1, &sa_obj);
1535         if (error != 0 && error != ENOENT)
1536                 return (error);
1537
1538         error = sa_setup(osp, sa_obj, zfs_attr_table, ZPL_END, sa_table);
1539         return (error);
1540 }
1541
1542 static int
1543 zfs_grab_sa_handle(objset_t *osp, uint64_t obj, sa_handle_t **hdlp,
1544     dmu_buf_t **db)
1545 {
1546         dmu_object_info_t doi;
1547         int error;
1548
1549         if ((error = sa_buf_hold(osp, obj, FTAG, db)) != 0)
1550                 return (error);
1551
1552         dmu_object_info_from_db(*db, &doi);
1553         if ((doi.doi_bonus_type != DMU_OT_SA &&
1554             doi.doi_bonus_type != DMU_OT_ZNODE) ||
1555             (doi.doi_bonus_type == DMU_OT_ZNODE &&
1556             doi.doi_bonus_size < sizeof (znode_phys_t))) {
1557                 sa_buf_rele(*db, FTAG);
1558                 return (ENOTSUP);
1559         }
1560
1561         error = sa_handle_get(osp, obj, NULL, SA_HDL_PRIVATE, hdlp);
1562         if (error != 0) {
1563                 sa_buf_rele(*db, FTAG);
1564                 return (error);
1565         }
1566
1567         return (0);
1568 }
1569
1570 void
1571 zfs_release_sa_handle(sa_handle_t *hdl, dmu_buf_t *db)
1572 {
1573         sa_handle_destroy(hdl);
1574         sa_buf_rele(db, FTAG);
1575 }
1576
1577 /*
1578  * Given an object number, return its parent object number and whether
1579  * or not the object is an extended attribute directory.
1580  */
1581 static int
1582 zfs_obj_to_pobj(sa_handle_t *hdl, sa_attr_type_t *sa_table, uint64_t *pobjp,
1583     int *is_xattrdir)
1584 {
1585         uint64_t parent;
1586         uint64_t pflags;
1587         uint64_t mode;
1588         sa_bulk_attr_t bulk[3];
1589         int count = 0;
1590         int error;
1591
1592         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_PARENT], NULL,
1593             &parent, sizeof (parent));
1594         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_FLAGS], NULL,
1595             &pflags, sizeof (pflags));
1596         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_MODE], NULL,
1597             &mode, sizeof (mode));
1598
1599         if ((error = sa_bulk_lookup(hdl, bulk, count)) != 0)
1600                 return (error);
1601
1602         *pobjp = parent;
1603         *is_xattrdir = ((pflags & ZFS_XATTR) != 0) && S_ISDIR(mode);
1604
1605         return (0);
1606 }
1607
1608 /*
1609  * Given an object number, return some zpl level statistics
1610  */
1611 static int
1612 zfs_obj_to_stats_impl(sa_handle_t *hdl, sa_attr_type_t *sa_table,
1613     zfs_stat_t *sb)
1614 {
1615         sa_bulk_attr_t bulk[4];
1616         int count = 0;
1617
1618         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_MODE], NULL,
1619             &sb->zs_mode, sizeof (sb->zs_mode));
1620         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_GEN], NULL,
1621             &sb->zs_gen, sizeof (sb->zs_gen));
1622         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_LINKS], NULL,
1623             &sb->zs_links, sizeof (sb->zs_links));
1624         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_CTIME], NULL,
1625             &sb->zs_ctime, sizeof (sb->zs_ctime));
1626
1627         return (sa_bulk_lookup(hdl, bulk, count));
1628 }
1629
1630 static int
1631 zfs_obj_to_path_impl(objset_t *osp, uint64_t obj, sa_handle_t *hdl,
1632     sa_attr_type_t *sa_table, char *buf, int len)
1633 {
1634         sa_handle_t *sa_hdl;
1635         sa_handle_t *prevhdl = NULL;
1636         dmu_buf_t *prevdb = NULL;
1637         dmu_buf_t *sa_db = NULL;
1638         char *path = buf + len - 1;
1639         int error;
1640
1641         *path = '\0';
1642         sa_hdl = hdl;
1643
1644         for (;;) {
1645                 uint64_t pobj;
1646                 char component[MAXNAMELEN + 2];
1647                 size_t complen;
1648                 int is_xattrdir;
1649
1650                 if (prevdb)
1651                         zfs_release_sa_handle(prevhdl, prevdb);
1652
1653                 if ((error = zfs_obj_to_pobj(sa_hdl, sa_table, &pobj,
1654                     &is_xattrdir)) != 0)
1655                         break;
1656
1657                 if (pobj == obj) {
1658                         if (path[0] != '/')
1659                                 *--path = '/';
1660                         break;
1661                 }
1662
1663                 component[0] = '/';
1664                 if (is_xattrdir) {
1665                         (void) sprintf(component + 1, "<xattrdir>");
1666                 } else {
1667                         error = zap_value_search(osp, pobj, obj,
1668                             ZFS_DIRENT_OBJ(-1ULL), component + 1);
1669                         if (error != 0)
1670                                 break;
1671                 }
1672
1673                 complen = strlen(component);
1674                 path -= complen;
1675                 ASSERT(path >= buf);
1676                 bcopy(component, path, complen);
1677                 obj = pobj;
1678
1679                 if (sa_hdl != hdl) {
1680                         prevhdl = sa_hdl;
1681                         prevdb = sa_db;
1682                 }
1683                 error = zfs_grab_sa_handle(osp, obj, &sa_hdl, &sa_db);
1684                 if (error != 0) {
1685                         sa_hdl = prevhdl;
1686                         sa_db = prevdb;
1687                         break;
1688                 }
1689         }
1690
1691         if (sa_hdl != NULL && sa_hdl != hdl) {
1692                 ASSERT(sa_db != NULL);
1693                 zfs_release_sa_handle(sa_hdl, sa_db);
1694         }
1695
1696         if (error == 0)
1697                 (void) memmove(buf, path, buf + len - path);
1698
1699         return (error);
1700 }
1701
1702 int
1703 zfs_obj_to_path(objset_t *osp, uint64_t obj, char *buf, int len)
1704 {
1705         sa_attr_type_t *sa_table;
1706         sa_handle_t *hdl;
1707         dmu_buf_t *db;
1708         int error;
1709
1710         error = zfs_sa_setup(osp, &sa_table);
1711         if (error != 0)
1712                 return (error);
1713
1714         error = zfs_grab_sa_handle(osp, obj, &hdl, &db);
1715         if (error != 0)
1716                 return (error);
1717
1718         error = zfs_obj_to_path_impl(osp, obj, hdl, sa_table, buf, len);
1719
1720         zfs_release_sa_handle(hdl, db);
1721         return (error);
1722 }
1723
1724 int
1725 zfs_obj_to_stats(objset_t *osp, uint64_t obj, zfs_stat_t *sb,
1726     char *buf, int len)
1727 {
1728         char *path = buf + len - 1;
1729         sa_attr_type_t *sa_table;
1730         sa_handle_t *hdl;
1731         dmu_buf_t *db;
1732         int error;
1733
1734         *path = '\0';
1735
1736         error = zfs_sa_setup(osp, &sa_table);
1737         if (error != 0)
1738                 return (error);
1739
1740         error = zfs_grab_sa_handle(osp, obj, &hdl, &db);
1741         if (error != 0)
1742                 return (error);
1743
1744         error = zfs_obj_to_stats_impl(hdl, sa_table, sb);
1745         if (error != 0) {
1746                 zfs_release_sa_handle(hdl, db);
1747                 return (error);
1748         }
1749
1750         error = zfs_obj_to_path_impl(osp, obj, hdl, sa_table, buf, len);
1751
1752         zfs_release_sa_handle(hdl, db);
1753         return (error);
1754 }
1755
1756 #if defined(_KERNEL) && defined(HAVE_SPL)
1757 EXPORT_SYMBOL(zfs_create_fs);
1758 EXPORT_SYMBOL(zfs_obj_to_path);
1759 #endif