]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/zfs/zfs_znode.c
Fix `zfs set atime|relatime=off|on` behavior on inherited datasets
[FreeBSD/FreeBSD.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  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
24  */
25
26 /* Portions Copyright 2007 Jeremy Teo */
27
28 #ifdef _KERNEL
29 #include <sys/types.h>
30 #include <sys/param.h>
31 #include <sys/time.h>
32 #include <sys/sysmacros.h>
33 #include <sys/mntent.h>
34 #include <sys/u8_textprep.h>
35 #include <sys/dsl_dataset.h>
36 #include <sys/vfs.h>
37 #include <sys/vnode.h>
38 #include <sys/file.h>
39 #include <sys/kmem.h>
40 #include <sys/errno.h>
41 #include <sys/mode.h>
42 #include <sys/atomic.h>
43 #include <sys/zfs_dir.h>
44 #include <sys/zfs_acl.h>
45 #include <sys/zfs_ioctl.h>
46 #include <sys/zfs_rlock.h>
47 #include <sys/zfs_fuid.h>
48 #include <sys/zfs_vnops.h>
49 #include <sys/zfs_ctldir.h>
50 #include <sys/dnode.h>
51 #include <sys/fs/zfs.h>
52 #include <sys/zpl.h>
53 #endif /* _KERNEL */
54
55 #include <sys/dmu.h>
56 #include <sys/dmu_objset.h>
57 #include <sys/dmu_tx.h>
58 #include <sys/refcount.h>
59 #include <sys/stat.h>
60 #include <sys/zap.h>
61 #include <sys/zfs_znode.h>
62 #include <sys/sa.h>
63 #include <sys/zfs_sa.h>
64 #include <sys/zfs_stat.h>
65
66 #include "zfs_prop.h"
67 #include "zfs_comutil.h"
68
69 /*
70  * Functions needed for userland (ie: libzpool) are not put under
71  * #ifdef_KERNEL; the rest of the functions have dependencies
72  * (such as VFS logic) that will not compile easily in userland.
73  */
74 #ifdef _KERNEL
75
76 static kmem_cache_t *znode_cache = NULL;
77 static kmem_cache_t *znode_hold_cache = NULL;
78 unsigned int zfs_object_mutex_size = ZFS_OBJ_MTX_SZ;
79
80 /*
81  * This is used by the test suite so that it can delay znodes from being
82  * freed in order to inspect the unlinked set.
83  */
84 int zfs_unlink_suspend_progress = 0;
85
86 /*
87  * This callback is invoked when acquiring a RL_WRITER or RL_APPEND lock on
88  * z_rangelock. It will modify the offset and length of the lock to reflect
89  * znode-specific information, and convert RL_APPEND to RL_WRITER.  This is
90  * called with the rangelock_t's rl_lock held, which avoids races.
91  */
92 static void
93 zfs_rangelock_cb(locked_range_t *new, void *arg)
94 {
95         znode_t *zp = arg;
96
97         /*
98          * If in append mode, convert to writer and lock starting at the
99          * current end of file.
100          */
101         if (new->lr_type == RL_APPEND) {
102                 new->lr_offset = zp->z_size;
103                 new->lr_type = RL_WRITER;
104         }
105
106         /*
107          * If we need to grow the block size then lock the whole file range.
108          */
109         uint64_t end_size = MAX(zp->z_size, new->lr_offset + new->lr_length);
110         if (end_size > zp->z_blksz && (!ISP2(zp->z_blksz) ||
111             zp->z_blksz < ZTOZSB(zp)->z_max_blksz)) {
112                 new->lr_offset = 0;
113                 new->lr_length = UINT64_MAX;
114         }
115 }
116
117 /*ARGSUSED*/
118 static int
119 zfs_znode_cache_constructor(void *buf, void *arg, int kmflags)
120 {
121         znode_t *zp = buf;
122
123         inode_init_once(ZTOI(zp));
124         list_link_init(&zp->z_link_node);
125
126         mutex_init(&zp->z_lock, NULL, MUTEX_DEFAULT, NULL);
127         rw_init(&zp->z_parent_lock, NULL, RW_DEFAULT, NULL);
128         rw_init(&zp->z_name_lock, NULL, RW_NOLOCKDEP, NULL);
129         mutex_init(&zp->z_acl_lock, NULL, MUTEX_DEFAULT, NULL);
130         rw_init(&zp->z_xattr_lock, NULL, RW_DEFAULT, NULL);
131
132         rangelock_init(&zp->z_rangelock, zfs_rangelock_cb, zp);
133
134         zp->z_dirlocks = NULL;
135         zp->z_acl_cached = NULL;
136         zp->z_xattr_cached = NULL;
137         zp->z_xattr_parent = 0;
138         zp->z_moved = 0;
139         return (0);
140 }
141
142 /*ARGSUSED*/
143 static void
144 zfs_znode_cache_destructor(void *buf, void *arg)
145 {
146         znode_t *zp = buf;
147
148         ASSERT(!list_link_active(&zp->z_link_node));
149         mutex_destroy(&zp->z_lock);
150         rw_destroy(&zp->z_parent_lock);
151         rw_destroy(&zp->z_name_lock);
152         mutex_destroy(&zp->z_acl_lock);
153         rw_destroy(&zp->z_xattr_lock);
154         rangelock_fini(&zp->z_rangelock);
155
156         ASSERT(zp->z_dirlocks == NULL);
157         ASSERT(zp->z_acl_cached == NULL);
158         ASSERT(zp->z_xattr_cached == NULL);
159 }
160
161 static int
162 zfs_znode_hold_cache_constructor(void *buf, void *arg, int kmflags)
163 {
164         znode_hold_t *zh = buf;
165
166         mutex_init(&zh->zh_lock, NULL, MUTEX_DEFAULT, NULL);
167         zfs_refcount_create(&zh->zh_refcount);
168         zh->zh_obj = ZFS_NO_OBJECT;
169
170         return (0);
171 }
172
173 static void
174 zfs_znode_hold_cache_destructor(void *buf, void *arg)
175 {
176         znode_hold_t *zh = buf;
177
178         mutex_destroy(&zh->zh_lock);
179         zfs_refcount_destroy(&zh->zh_refcount);
180 }
181
182 void
183 zfs_znode_init(void)
184 {
185         /*
186          * Initialize zcache.  The KMC_SLAB hint is used in order that it be
187          * backed by kmalloc() when on the Linux slab in order that any
188          * wait_on_bit() operations on the related inode operate properly.
189          */
190         ASSERT(znode_cache == NULL);
191         znode_cache = kmem_cache_create("zfs_znode_cache",
192             sizeof (znode_t), 0, zfs_znode_cache_constructor,
193             zfs_znode_cache_destructor, NULL, NULL, NULL, KMC_SLAB);
194
195         ASSERT(znode_hold_cache == NULL);
196         znode_hold_cache = kmem_cache_create("zfs_znode_hold_cache",
197             sizeof (znode_hold_t), 0, zfs_znode_hold_cache_constructor,
198             zfs_znode_hold_cache_destructor, NULL, NULL, NULL, 0);
199 }
200
201 void
202 zfs_znode_fini(void)
203 {
204         /*
205          * Cleanup zcache
206          */
207         if (znode_cache)
208                 kmem_cache_destroy(znode_cache);
209         znode_cache = NULL;
210
211         if (znode_hold_cache)
212                 kmem_cache_destroy(znode_hold_cache);
213         znode_hold_cache = NULL;
214 }
215
216 /*
217  * The zfs_znode_hold_enter() / zfs_znode_hold_exit() functions are used to
218  * serialize access to a znode and its SA buffer while the object is being
219  * created or destroyed.  This kind of locking would normally reside in the
220  * znode itself but in this case that's impossible because the znode and SA
221  * buffer may not yet exist.  Therefore the locking is handled externally
222  * with an array of mutexs and AVLs trees which contain per-object locks.
223  *
224  * In zfs_znode_hold_enter() a per-object lock is created as needed, inserted
225  * in to the correct AVL tree and finally the per-object lock is held.  In
226  * zfs_znode_hold_exit() the process is reversed.  The per-object lock is
227  * released, removed from the AVL tree and destroyed if there are no waiters.
228  *
229  * This scheme has two important properties:
230  *
231  * 1) No memory allocations are performed while holding one of the z_hold_locks.
232  *    This ensures evict(), which can be called from direct memory reclaim, will
233  *    never block waiting on a z_hold_locks which just happens to have hashed
234  *    to the same index.
235  *
236  * 2) All locks used to serialize access to an object are per-object and never
237  *    shared.  This minimizes lock contention without creating a large number
238  *    of dedicated locks.
239  *
240  * On the downside it does require znode_lock_t structures to be frequently
241  * allocated and freed.  However, because these are backed by a kmem cache
242  * and very short lived this cost is minimal.
243  */
244 int
245 zfs_znode_hold_compare(const void *a, const void *b)
246 {
247         const znode_hold_t *zh_a = (const znode_hold_t *)a;
248         const znode_hold_t *zh_b = (const znode_hold_t *)b;
249
250         return (AVL_CMP(zh_a->zh_obj, zh_b->zh_obj));
251 }
252
253 boolean_t
254 zfs_znode_held(zfsvfs_t *zfsvfs, uint64_t obj)
255 {
256         znode_hold_t *zh, search;
257         int i = ZFS_OBJ_HASH(zfsvfs, obj);
258         boolean_t held;
259
260         search.zh_obj = obj;
261
262         mutex_enter(&zfsvfs->z_hold_locks[i]);
263         zh = avl_find(&zfsvfs->z_hold_trees[i], &search, NULL);
264         held = (zh && MUTEX_HELD(&zh->zh_lock)) ? B_TRUE : B_FALSE;
265         mutex_exit(&zfsvfs->z_hold_locks[i]);
266
267         return (held);
268 }
269
270 static znode_hold_t *
271 zfs_znode_hold_enter(zfsvfs_t *zfsvfs, uint64_t obj)
272 {
273         znode_hold_t *zh, *zh_new, search;
274         int i = ZFS_OBJ_HASH(zfsvfs, obj);
275         boolean_t found = B_FALSE;
276
277         zh_new = kmem_cache_alloc(znode_hold_cache, KM_SLEEP);
278         zh_new->zh_obj = obj;
279         search.zh_obj = obj;
280
281         mutex_enter(&zfsvfs->z_hold_locks[i]);
282         zh = avl_find(&zfsvfs->z_hold_trees[i], &search, NULL);
283         if (likely(zh == NULL)) {
284                 zh = zh_new;
285                 avl_add(&zfsvfs->z_hold_trees[i], zh);
286         } else {
287                 ASSERT3U(zh->zh_obj, ==, obj);
288                 found = B_TRUE;
289         }
290         zfs_refcount_add(&zh->zh_refcount, NULL);
291         mutex_exit(&zfsvfs->z_hold_locks[i]);
292
293         if (found == B_TRUE)
294                 kmem_cache_free(znode_hold_cache, zh_new);
295
296         ASSERT(MUTEX_NOT_HELD(&zh->zh_lock));
297         ASSERT3S(zfs_refcount_count(&zh->zh_refcount), >, 0);
298         mutex_enter(&zh->zh_lock);
299
300         return (zh);
301 }
302
303 static void
304 zfs_znode_hold_exit(zfsvfs_t *zfsvfs, znode_hold_t *zh)
305 {
306         int i = ZFS_OBJ_HASH(zfsvfs, zh->zh_obj);
307         boolean_t remove = B_FALSE;
308
309         ASSERT(zfs_znode_held(zfsvfs, zh->zh_obj));
310         ASSERT3S(zfs_refcount_count(&zh->zh_refcount), >, 0);
311         mutex_exit(&zh->zh_lock);
312
313         mutex_enter(&zfsvfs->z_hold_locks[i]);
314         if (zfs_refcount_remove(&zh->zh_refcount, NULL) == 0) {
315                 avl_remove(&zfsvfs->z_hold_trees[i], zh);
316                 remove = B_TRUE;
317         }
318         mutex_exit(&zfsvfs->z_hold_locks[i]);
319
320         if (remove == B_TRUE)
321                 kmem_cache_free(znode_hold_cache, zh);
322 }
323
324 static void
325 zfs_znode_sa_init(zfsvfs_t *zfsvfs, znode_t *zp,
326     dmu_buf_t *db, dmu_object_type_t obj_type, sa_handle_t *sa_hdl)
327 {
328         ASSERT(zfs_znode_held(zfsvfs, zp->z_id));
329
330         mutex_enter(&zp->z_lock);
331
332         ASSERT(zp->z_sa_hdl == NULL);
333         ASSERT(zp->z_acl_cached == NULL);
334         if (sa_hdl == NULL) {
335                 VERIFY(0 == sa_handle_get_from_db(zfsvfs->z_os, db, zp,
336                     SA_HDL_SHARED, &zp->z_sa_hdl));
337         } else {
338                 zp->z_sa_hdl = sa_hdl;
339                 sa_set_userp(sa_hdl, zp);
340         }
341
342         zp->z_is_sa = (obj_type == DMU_OT_SA) ? B_TRUE : B_FALSE;
343
344         mutex_exit(&zp->z_lock);
345 }
346
347 void
348 zfs_znode_dmu_fini(znode_t *zp)
349 {
350         ASSERT(zfs_znode_held(ZTOZSB(zp), zp->z_id) || zp->z_unlinked ||
351             RW_WRITE_HELD(&ZTOZSB(zp)->z_teardown_inactive_lock));
352
353         sa_handle_destroy(zp->z_sa_hdl);
354         zp->z_sa_hdl = NULL;
355 }
356
357 /*
358  * Called by new_inode() to allocate a new inode.
359  */
360 int
361 zfs_inode_alloc(struct super_block *sb, struct inode **ip)
362 {
363         znode_t *zp;
364
365         zp = kmem_cache_alloc(znode_cache, KM_SLEEP);
366         *ip = ZTOI(zp);
367
368         return (0);
369 }
370
371 /*
372  * Called in multiple places when an inode should be destroyed.
373  */
374 void
375 zfs_inode_destroy(struct inode *ip)
376 {
377         znode_t *zp = ITOZ(ip);
378         zfsvfs_t *zfsvfs = ZTOZSB(zp);
379
380         mutex_enter(&zfsvfs->z_znodes_lock);
381         if (list_link_active(&zp->z_link_node)) {
382                 list_remove(&zfsvfs->z_all_znodes, zp);
383                 zfsvfs->z_nr_znodes--;
384         }
385         mutex_exit(&zfsvfs->z_znodes_lock);
386
387         if (zp->z_acl_cached) {
388                 zfs_acl_free(zp->z_acl_cached);
389                 zp->z_acl_cached = NULL;
390         }
391
392         if (zp->z_xattr_cached) {
393                 nvlist_free(zp->z_xattr_cached);
394                 zp->z_xattr_cached = NULL;
395         }
396
397         kmem_cache_free(znode_cache, zp);
398 }
399
400 static void
401 zfs_inode_set_ops(zfsvfs_t *zfsvfs, struct inode *ip)
402 {
403         uint64_t rdev = 0;
404
405         switch (ip->i_mode & S_IFMT) {
406         case S_IFREG:
407                 ip->i_op = &zpl_inode_operations;
408                 ip->i_fop = &zpl_file_operations;
409                 ip->i_mapping->a_ops = &zpl_address_space_operations;
410                 break;
411
412         case S_IFDIR:
413                 ip->i_op = &zpl_dir_inode_operations;
414                 ip->i_fop = &zpl_dir_file_operations;
415                 ITOZ(ip)->z_zn_prefetch = B_TRUE;
416                 break;
417
418         case S_IFLNK:
419                 ip->i_op = &zpl_symlink_inode_operations;
420                 break;
421
422         /*
423          * rdev is only stored in a SA only for device files.
424          */
425         case S_IFCHR:
426         case S_IFBLK:
427                 (void) sa_lookup(ITOZ(ip)->z_sa_hdl, SA_ZPL_RDEV(zfsvfs), &rdev,
428                     sizeof (rdev));
429                 /*FALLTHROUGH*/
430         case S_IFIFO:
431         case S_IFSOCK:
432                 init_special_inode(ip, ip->i_mode, rdev);
433                 ip->i_op = &zpl_special_inode_operations;
434                 break;
435
436         default:
437                 zfs_panic_recover("inode %llu has invalid mode: 0x%x\n",
438                     (u_longlong_t)ip->i_ino, ip->i_mode);
439
440                 /* Assume the inode is a file and attempt to continue */
441                 ip->i_mode = S_IFREG | 0644;
442                 ip->i_op = &zpl_inode_operations;
443                 ip->i_fop = &zpl_file_operations;
444                 ip->i_mapping->a_ops = &zpl_address_space_operations;
445                 break;
446         }
447 }
448
449 void
450 zfs_set_inode_flags(znode_t *zp, struct inode *ip)
451 {
452         /*
453          * Linux and Solaris have different sets of file attributes, so we
454          * restrict this conversion to the intersection of the two.
455          */
456 #ifdef HAVE_INODE_SET_FLAGS
457         unsigned int flags = 0;
458         if (zp->z_pflags & ZFS_IMMUTABLE)
459                 flags |= S_IMMUTABLE;
460         if (zp->z_pflags & ZFS_APPENDONLY)
461                 flags |= S_APPEND;
462
463         inode_set_flags(ip, flags, S_IMMUTABLE|S_APPEND);
464 #else
465         if (zp->z_pflags & ZFS_IMMUTABLE)
466                 ip->i_flags |= S_IMMUTABLE;
467         else
468                 ip->i_flags &= ~S_IMMUTABLE;
469
470         if (zp->z_pflags & ZFS_APPENDONLY)
471                 ip->i_flags |= S_APPEND;
472         else
473                 ip->i_flags &= ~S_APPEND;
474 #endif
475 }
476
477 /*
478  * Update the embedded inode given the znode.  We should work toward
479  * eliminating this function as soon as possible by removing values
480  * which are duplicated between the znode and inode.  If the generic
481  * inode has the correct field it should be used, and the ZFS code
482  * updated to access the inode.  This can be done incrementally.
483  */
484 void
485 zfs_inode_update(znode_t *zp)
486 {
487         zfsvfs_t        *zfsvfs;
488         struct inode    *ip;
489         uint32_t        blksize;
490         u_longlong_t    i_blocks;
491
492         ASSERT(zp != NULL);
493         zfsvfs = ZTOZSB(zp);
494         ip = ZTOI(zp);
495
496         /* Skip .zfs control nodes which do not exist on disk. */
497         if (zfsctl_is_node(ip))
498                 return;
499
500         dmu_object_size_from_db(sa_get_db(zp->z_sa_hdl), &blksize, &i_blocks);
501
502         spin_lock(&ip->i_lock);
503         ip->i_blocks = i_blocks;
504         i_size_write(ip, zp->z_size);
505         spin_unlock(&ip->i_lock);
506 }
507
508
509 /*
510  * Construct a znode+inode and initialize.
511  *
512  * This does not do a call to dmu_set_user() that is
513  * up to the caller to do, in case you don't want to
514  * return the znode
515  */
516 static znode_t *
517 zfs_znode_alloc(zfsvfs_t *zfsvfs, dmu_buf_t *db, int blksz,
518     dmu_object_type_t obj_type, uint64_t obj, sa_handle_t *hdl)
519 {
520         znode_t *zp;
521         struct inode *ip;
522         uint64_t mode;
523         uint64_t parent;
524         uint64_t tmp_gen;
525         uint64_t links;
526         uint64_t z_uid, z_gid;
527         uint64_t atime[2], mtime[2], ctime[2];
528         uint64_t projid = ZFS_DEFAULT_PROJID;
529         sa_bulk_attr_t bulk[11];
530         int count = 0;
531
532         ASSERT(zfsvfs != NULL);
533
534         ip = new_inode(zfsvfs->z_sb);
535         if (ip == NULL)
536                 return (NULL);
537
538         zp = ITOZ(ip);
539         ASSERT(zp->z_dirlocks == NULL);
540         ASSERT3P(zp->z_acl_cached, ==, NULL);
541         ASSERT3P(zp->z_xattr_cached, ==, NULL);
542         zp->z_moved = 0;
543         zp->z_sa_hdl = NULL;
544         zp->z_unlinked = 0;
545         zp->z_atime_dirty = 0;
546         zp->z_mapcnt = 0;
547         zp->z_id = db->db_object;
548         zp->z_blksz = blksz;
549         zp->z_seq = 0x7A4653;
550         zp->z_sync_cnt = 0;
551         zp->z_is_mapped = B_FALSE;
552         zp->z_is_ctldir = B_FALSE;
553         zp->z_is_stale = B_FALSE;
554
555         zfs_znode_sa_init(zfsvfs, zp, db, obj_type, hdl);
556
557         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL, &mode, 8);
558         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zfsvfs), NULL, &tmp_gen, 8);
559         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
560             &zp->z_size, 8);
561         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL, &links, 8);
562         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
563             &zp->z_pflags, 8);
564         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PARENT(zfsvfs), NULL,
565             &parent, 8);
566         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL, &z_uid, 8);
567         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL, &z_gid, 8);
568         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL, &atime, 16);
569         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
570         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
571
572         if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count) != 0 || tmp_gen == 0 ||
573             (dmu_objset_projectquota_enabled(zfsvfs->z_os) &&
574             (zp->z_pflags & ZFS_PROJID) &&
575             sa_lookup(zp->z_sa_hdl, SA_ZPL_PROJID(zfsvfs), &projid, 8) != 0)) {
576                 if (hdl == NULL)
577                         sa_handle_destroy(zp->z_sa_hdl);
578                 zp->z_sa_hdl = NULL;
579                 goto error;
580         }
581
582         zp->z_projid = projid;
583         zp->z_mode = ip->i_mode = mode;
584         ip->i_generation = (uint32_t)tmp_gen;
585         ip->i_blkbits = SPA_MINBLOCKSHIFT;
586         set_nlink(ip, (uint32_t)links);
587         zfs_uid_write(ip, z_uid);
588         zfs_gid_write(ip, z_gid);
589         zfs_set_inode_flags(zp, ip);
590
591         /* Cache the xattr parent id */
592         if (zp->z_pflags & ZFS_XATTR)
593                 zp->z_xattr_parent = parent;
594
595         ZFS_TIME_DECODE(&ip->i_atime, atime);
596         ZFS_TIME_DECODE(&ip->i_mtime, mtime);
597         ZFS_TIME_DECODE(&ip->i_ctime, ctime);
598
599         ip->i_ino = obj;
600         zfs_inode_update(zp);
601         zfs_inode_set_ops(zfsvfs, ip);
602
603         /*
604          * The only way insert_inode_locked() can fail is if the ip->i_ino
605          * number is already hashed for this super block.  This can never
606          * happen because the inode numbers map 1:1 with the object numbers.
607          *
608          * The one exception is rolling back a mounted file system, but in
609          * this case all the active inode are unhashed during the rollback.
610          */
611         VERIFY3S(insert_inode_locked(ip), ==, 0);
612
613         mutex_enter(&zfsvfs->z_znodes_lock);
614         list_insert_tail(&zfsvfs->z_all_znodes, zp);
615         zfsvfs->z_nr_znodes++;
616         membar_producer();
617         mutex_exit(&zfsvfs->z_znodes_lock);
618
619         unlock_new_inode(ip);
620         return (zp);
621
622 error:
623         iput(ip);
624         return (NULL);
625 }
626
627 /*
628  * Safely mark an inode dirty.  Inodes which are part of a read-only
629  * file system or snapshot may not be dirtied.
630  */
631 void
632 zfs_mark_inode_dirty(struct inode *ip)
633 {
634         zfsvfs_t *zfsvfs = ITOZSB(ip);
635
636         if (zfs_is_readonly(zfsvfs) || dmu_objset_is_snapshot(zfsvfs->z_os))
637                 return;
638
639         mark_inode_dirty(ip);
640 }
641
642 static uint64_t empty_xattr;
643 static uint64_t pad[4];
644 static zfs_acl_phys_t acl_phys;
645 /*
646  * Create a new DMU object to hold a zfs znode.
647  *
648  *      IN:     dzp     - parent directory for new znode
649  *              vap     - file attributes for new znode
650  *              tx      - dmu transaction id for zap operations
651  *              cr      - credentials of caller
652  *              flag    - flags:
653  *                        IS_ROOT_NODE  - new object will be root
654  *                        IS_XATTR      - new object is an attribute
655  *              bonuslen - length of bonus buffer
656  *              setaclp  - File/Dir initial ACL
657  *              fuidp    - Tracks fuid allocation.
658  *
659  *      OUT:    zpp     - allocated znode
660  *
661  */
662 void
663 zfs_mknode(znode_t *dzp, vattr_t *vap, dmu_tx_t *tx, cred_t *cr,
664     uint_t flag, znode_t **zpp, zfs_acl_ids_t *acl_ids)
665 {
666         uint64_t        crtime[2], atime[2], mtime[2], ctime[2];
667         uint64_t        mode, size, links, parent, pflags;
668         uint64_t        projid = ZFS_DEFAULT_PROJID;
669         uint64_t        rdev = 0;
670         zfsvfs_t        *zfsvfs = ZTOZSB(dzp);
671         dmu_buf_t       *db;
672         inode_timespec_t now;
673         uint64_t        gen, obj;
674         int             bonuslen;
675         int             dnodesize;
676         sa_handle_t     *sa_hdl;
677         dmu_object_type_t obj_type;
678         sa_bulk_attr_t  *sa_attrs;
679         int             cnt = 0;
680         zfs_acl_locator_cb_t locate = { 0 };
681         znode_hold_t    *zh;
682
683         if (zfsvfs->z_replay) {
684                 obj = vap->va_nodeid;
685                 now = vap->va_ctime;            /* see zfs_replay_create() */
686                 gen = vap->va_nblocks;          /* ditto */
687                 dnodesize = vap->va_fsid;       /* ditto */
688         } else {
689                 obj = 0;
690                 gethrestime(&now);
691                 gen = dmu_tx_get_txg(tx);
692                 dnodesize = dmu_objset_dnodesize(zfsvfs->z_os);
693         }
694
695         if (dnodesize == 0)
696                 dnodesize = DNODE_MIN_SIZE;
697
698         obj_type = zfsvfs->z_use_sa ? DMU_OT_SA : DMU_OT_ZNODE;
699
700         bonuslen = (obj_type == DMU_OT_SA) ?
701             DN_BONUS_SIZE(dnodesize) : ZFS_OLD_ZNODE_PHYS_SIZE;
702
703         /*
704          * Create a new DMU object.
705          */
706         /*
707          * There's currently no mechanism for pre-reading the blocks that will
708          * be needed to allocate a new object, so we accept the small chance
709          * that there will be an i/o error and we will fail one of the
710          * assertions below.
711          */
712         if (S_ISDIR(vap->va_mode)) {
713                 if (zfsvfs->z_replay) {
714                         VERIFY0(zap_create_claim_norm_dnsize(zfsvfs->z_os, obj,
715                             zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
716                             obj_type, bonuslen, dnodesize, tx));
717                 } else {
718                         obj = zap_create_norm_dnsize(zfsvfs->z_os,
719                             zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
720                             obj_type, bonuslen, dnodesize, tx);
721                 }
722         } else {
723                 if (zfsvfs->z_replay) {
724                         VERIFY0(dmu_object_claim_dnsize(zfsvfs->z_os, obj,
725                             DMU_OT_PLAIN_FILE_CONTENTS, 0,
726                             obj_type, bonuslen, dnodesize, tx));
727                 } else {
728                         obj = dmu_object_alloc_dnsize(zfsvfs->z_os,
729                             DMU_OT_PLAIN_FILE_CONTENTS, 0,
730                             obj_type, bonuslen, dnodesize, tx);
731                 }
732         }
733
734         zh = zfs_znode_hold_enter(zfsvfs, obj);
735         VERIFY0(sa_buf_hold(zfsvfs->z_os, obj, NULL, &db));
736
737         /*
738          * If this is the root, fix up the half-initialized parent pointer
739          * to reference the just-allocated physical data area.
740          */
741         if (flag & IS_ROOT_NODE) {
742                 dzp->z_id = obj;
743         }
744
745         /*
746          * If parent is an xattr, so am I.
747          */
748         if (dzp->z_pflags & ZFS_XATTR) {
749                 flag |= IS_XATTR;
750         }
751
752         if (zfsvfs->z_use_fuids)
753                 pflags = ZFS_ARCHIVE | ZFS_AV_MODIFIED;
754         else
755                 pflags = 0;
756
757         if (S_ISDIR(vap->va_mode)) {
758                 size = 2;               /* contents ("." and "..") */
759                 links = 2;
760         } else {
761                 size = 0;
762                 links = (flag & IS_TMPFILE) ? 0 : 1;
763         }
764
765         if (S_ISBLK(vap->va_mode) || S_ISCHR(vap->va_mode))
766                 rdev = vap->va_rdev;
767
768         parent = dzp->z_id;
769         mode = acl_ids->z_mode;
770         if (flag & IS_XATTR)
771                 pflags |= ZFS_XATTR;
772
773         if (S_ISREG(vap->va_mode) || S_ISDIR(vap->va_mode)) {
774                 /*
775                  * With ZFS_PROJID flag, we can easily know whether there is
776                  * project ID stored on disk or not. See zfs_space_delta_cb().
777                  */
778                 if (obj_type != DMU_OT_ZNODE &&
779                     dmu_objset_projectquota_enabled(zfsvfs->z_os))
780                         pflags |= ZFS_PROJID;
781
782                 /*
783                  * Inherit project ID from parent if required.
784                  */
785                 projid = zfs_inherit_projid(dzp);
786                 if (dzp->z_pflags & ZFS_PROJINHERIT)
787                         pflags |= ZFS_PROJINHERIT;
788         }
789
790         /*
791          * No execs denied will be deterimed when zfs_mode_compute() is called.
792          */
793         pflags |= acl_ids->z_aclp->z_hints &
794             (ZFS_ACL_TRIVIAL|ZFS_INHERIT_ACE|ZFS_ACL_AUTO_INHERIT|
795             ZFS_ACL_DEFAULTED|ZFS_ACL_PROTECTED);
796
797         ZFS_TIME_ENCODE(&now, crtime);
798         ZFS_TIME_ENCODE(&now, ctime);
799
800         if (vap->va_mask & ATTR_ATIME) {
801                 ZFS_TIME_ENCODE(&vap->va_atime, atime);
802         } else {
803                 ZFS_TIME_ENCODE(&now, atime);
804         }
805
806         if (vap->va_mask & ATTR_MTIME) {
807                 ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
808         } else {
809                 ZFS_TIME_ENCODE(&now, mtime);
810         }
811
812         /* Now add in all of the "SA" attributes */
813         VERIFY(0 == sa_handle_get_from_db(zfsvfs->z_os, db, NULL, SA_HDL_SHARED,
814             &sa_hdl));
815
816         /*
817          * Setup the array of attributes to be replaced/set on the new file
818          *
819          * order for  DMU_OT_ZNODE is critical since it needs to be constructed
820          * in the old znode_phys_t format.  Don't change this ordering
821          */
822         sa_attrs = kmem_alloc(sizeof (sa_bulk_attr_t) * ZPL_END, KM_SLEEP);
823
824         if (obj_type == DMU_OT_ZNODE) {
825                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ATIME(zfsvfs),
826                     NULL, &atime, 16);
827                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MTIME(zfsvfs),
828                     NULL, &mtime, 16);
829                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CTIME(zfsvfs),
830                     NULL, &ctime, 16);
831                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CRTIME(zfsvfs),
832                     NULL, &crtime, 16);
833                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GEN(zfsvfs),
834                     NULL, &gen, 8);
835                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MODE(zfsvfs),
836                     NULL, &mode, 8);
837                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_SIZE(zfsvfs),
838                     NULL, &size, 8);
839                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PARENT(zfsvfs),
840                     NULL, &parent, 8);
841         } else {
842                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MODE(zfsvfs),
843                     NULL, &mode, 8);
844                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_SIZE(zfsvfs),
845                     NULL, &size, 8);
846                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GEN(zfsvfs),
847                     NULL, &gen, 8);
848                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_UID(zfsvfs),
849                     NULL, &acl_ids->z_fuid, 8);
850                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GID(zfsvfs),
851                     NULL, &acl_ids->z_fgid, 8);
852                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PARENT(zfsvfs),
853                     NULL, &parent, 8);
854                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_FLAGS(zfsvfs),
855                     NULL, &pflags, 8);
856                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ATIME(zfsvfs),
857                     NULL, &atime, 16);
858                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MTIME(zfsvfs),
859                     NULL, &mtime, 16);
860                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CTIME(zfsvfs),
861                     NULL, &ctime, 16);
862                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CRTIME(zfsvfs),
863                     NULL, &crtime, 16);
864         }
865
866         SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_LINKS(zfsvfs), NULL, &links, 8);
867
868         if (obj_type == DMU_OT_ZNODE) {
869                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_XATTR(zfsvfs), NULL,
870                     &empty_xattr, 8);
871         } else if (dmu_objset_projectquota_enabled(zfsvfs->z_os) &&
872             pflags & ZFS_PROJID) {
873                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PROJID(zfsvfs),
874                     NULL, &projid, 8);
875         }
876         if (obj_type == DMU_OT_ZNODE ||
877             (S_ISBLK(vap->va_mode) || S_ISCHR(vap->va_mode))) {
878                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_RDEV(zfsvfs),
879                     NULL, &rdev, 8);
880         }
881         if (obj_type == DMU_OT_ZNODE) {
882                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_FLAGS(zfsvfs),
883                     NULL, &pflags, 8);
884                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_UID(zfsvfs), NULL,
885                     &acl_ids->z_fuid, 8);
886                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GID(zfsvfs), NULL,
887                     &acl_ids->z_fgid, 8);
888                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PAD(zfsvfs), NULL, pad,
889                     sizeof (uint64_t) * 4);
890                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ZNODE_ACL(zfsvfs), NULL,
891                     &acl_phys, sizeof (zfs_acl_phys_t));
892         } else if (acl_ids->z_aclp->z_version >= ZFS_ACL_VERSION_FUID) {
893                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_DACL_COUNT(zfsvfs), NULL,
894                     &acl_ids->z_aclp->z_acl_count, 8);
895                 locate.cb_aclp = acl_ids->z_aclp;
896                 SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_DACL_ACES(zfsvfs),
897                     zfs_acl_data_locator, &locate,
898                     acl_ids->z_aclp->z_acl_bytes);
899                 mode = zfs_mode_compute(mode, acl_ids->z_aclp, &pflags,
900                     acl_ids->z_fuid, acl_ids->z_fgid);
901         }
902
903         VERIFY(sa_replace_all_by_template(sa_hdl, sa_attrs, cnt, tx) == 0);
904
905         if (!(flag & IS_ROOT_NODE)) {
906                 /*
907                  * The call to zfs_znode_alloc() may fail if memory is low
908                  * via the call path: alloc_inode() -> inode_init_always() ->
909                  * security_inode_alloc() -> inode_alloc_security().  Since
910                  * the existing code is written such that zfs_mknode() can
911                  * not fail retry until sufficient memory has been reclaimed.
912                  */
913                 do {
914                         *zpp = zfs_znode_alloc(zfsvfs, db, 0, obj_type, obj,
915                             sa_hdl);
916                 } while (*zpp == NULL);
917
918                 VERIFY(*zpp != NULL);
919                 VERIFY(dzp != NULL);
920         } else {
921                 /*
922                  * If we are creating the root node, the "parent" we
923                  * passed in is the znode for the root.
924                  */
925                 *zpp = dzp;
926
927                 (*zpp)->z_sa_hdl = sa_hdl;
928         }
929
930         (*zpp)->z_pflags = pflags;
931         (*zpp)->z_mode = ZTOI(*zpp)->i_mode = mode;
932         (*zpp)->z_dnodesize = dnodesize;
933         (*zpp)->z_projid = projid;
934
935         if (obj_type == DMU_OT_ZNODE ||
936             acl_ids->z_aclp->z_version < ZFS_ACL_VERSION_FUID) {
937                 VERIFY0(zfs_aclset_common(*zpp, acl_ids->z_aclp, cr, tx));
938         }
939         kmem_free(sa_attrs, sizeof (sa_bulk_attr_t) * ZPL_END);
940         zfs_znode_hold_exit(zfsvfs, zh);
941 }
942
943 /*
944  * Update in-core attributes.  It is assumed the caller will be doing an
945  * sa_bulk_update to push the changes out.
946  */
947 void
948 zfs_xvattr_set(znode_t *zp, xvattr_t *xvap, dmu_tx_t *tx)
949 {
950         xoptattr_t *xoap;
951         boolean_t update_inode = B_FALSE;
952
953         xoap = xva_getxoptattr(xvap);
954         ASSERT(xoap);
955
956         if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
957                 uint64_t times[2];
958                 ZFS_TIME_ENCODE(&xoap->xoa_createtime, times);
959                 (void) sa_update(zp->z_sa_hdl, SA_ZPL_CRTIME(ZTOZSB(zp)),
960                     &times, sizeof (times), tx);
961                 XVA_SET_RTN(xvap, XAT_CREATETIME);
962         }
963         if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
964                 ZFS_ATTR_SET(zp, ZFS_READONLY, xoap->xoa_readonly,
965                     zp->z_pflags, tx);
966                 XVA_SET_RTN(xvap, XAT_READONLY);
967         }
968         if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
969                 ZFS_ATTR_SET(zp, ZFS_HIDDEN, xoap->xoa_hidden,
970                     zp->z_pflags, tx);
971                 XVA_SET_RTN(xvap, XAT_HIDDEN);
972         }
973         if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
974                 ZFS_ATTR_SET(zp, ZFS_SYSTEM, xoap->xoa_system,
975                     zp->z_pflags, tx);
976                 XVA_SET_RTN(xvap, XAT_SYSTEM);
977         }
978         if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
979                 ZFS_ATTR_SET(zp, ZFS_ARCHIVE, xoap->xoa_archive,
980                     zp->z_pflags, tx);
981                 XVA_SET_RTN(xvap, XAT_ARCHIVE);
982         }
983         if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
984                 ZFS_ATTR_SET(zp, ZFS_IMMUTABLE, xoap->xoa_immutable,
985                     zp->z_pflags, tx);
986                 XVA_SET_RTN(xvap, XAT_IMMUTABLE);
987
988                 update_inode = B_TRUE;
989         }
990         if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
991                 ZFS_ATTR_SET(zp, ZFS_NOUNLINK, xoap->xoa_nounlink,
992                     zp->z_pflags, tx);
993                 XVA_SET_RTN(xvap, XAT_NOUNLINK);
994         }
995         if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
996                 ZFS_ATTR_SET(zp, ZFS_APPENDONLY, xoap->xoa_appendonly,
997                     zp->z_pflags, tx);
998                 XVA_SET_RTN(xvap, XAT_APPENDONLY);
999
1000                 update_inode = B_TRUE;
1001         }
1002         if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
1003                 ZFS_ATTR_SET(zp, ZFS_NODUMP, xoap->xoa_nodump,
1004                     zp->z_pflags, tx);
1005                 XVA_SET_RTN(xvap, XAT_NODUMP);
1006         }
1007         if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
1008                 ZFS_ATTR_SET(zp, ZFS_OPAQUE, xoap->xoa_opaque,
1009                     zp->z_pflags, tx);
1010                 XVA_SET_RTN(xvap, XAT_OPAQUE);
1011         }
1012         if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
1013                 ZFS_ATTR_SET(zp, ZFS_AV_QUARANTINED,
1014                     xoap->xoa_av_quarantined, zp->z_pflags, tx);
1015                 XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
1016         }
1017         if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
1018                 ZFS_ATTR_SET(zp, ZFS_AV_MODIFIED, xoap->xoa_av_modified,
1019                     zp->z_pflags, tx);
1020                 XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
1021         }
1022         if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
1023                 zfs_sa_set_scanstamp(zp, xvap, tx);
1024                 XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
1025         }
1026         if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
1027                 ZFS_ATTR_SET(zp, ZFS_REPARSE, xoap->xoa_reparse,
1028                     zp->z_pflags, tx);
1029                 XVA_SET_RTN(xvap, XAT_REPARSE);
1030         }
1031         if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
1032                 ZFS_ATTR_SET(zp, ZFS_OFFLINE, xoap->xoa_offline,
1033                     zp->z_pflags, tx);
1034                 XVA_SET_RTN(xvap, XAT_OFFLINE);
1035         }
1036         if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
1037                 ZFS_ATTR_SET(zp, ZFS_SPARSE, xoap->xoa_sparse,
1038                     zp->z_pflags, tx);
1039                 XVA_SET_RTN(xvap, XAT_SPARSE);
1040         }
1041         if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
1042                 ZFS_ATTR_SET(zp, ZFS_PROJINHERIT, xoap->xoa_projinherit,
1043                     zp->z_pflags, tx);
1044                 XVA_SET_RTN(xvap, XAT_PROJINHERIT);
1045         }
1046
1047         if (update_inode)
1048                 zfs_set_inode_flags(zp, ZTOI(zp));
1049 }
1050
1051 int
1052 zfs_zget(zfsvfs_t *zfsvfs, uint64_t obj_num, znode_t **zpp)
1053 {
1054         dmu_object_info_t doi;
1055         dmu_buf_t       *db;
1056         znode_t         *zp;
1057         znode_hold_t    *zh;
1058         int err;
1059         sa_handle_t     *hdl;
1060
1061         *zpp = NULL;
1062
1063 again:
1064         zh = zfs_znode_hold_enter(zfsvfs, obj_num);
1065
1066         err = sa_buf_hold(zfsvfs->z_os, obj_num, NULL, &db);
1067         if (err) {
1068                 zfs_znode_hold_exit(zfsvfs, zh);
1069                 return (err);
1070         }
1071
1072         dmu_object_info_from_db(db, &doi);
1073         if (doi.doi_bonus_type != DMU_OT_SA &&
1074             (doi.doi_bonus_type != DMU_OT_ZNODE ||
1075             (doi.doi_bonus_type == DMU_OT_ZNODE &&
1076             doi.doi_bonus_size < sizeof (znode_phys_t)))) {
1077                 sa_buf_rele(db, NULL);
1078                 zfs_znode_hold_exit(zfsvfs, zh);
1079                 return (SET_ERROR(EINVAL));
1080         }
1081
1082         hdl = dmu_buf_get_user(db);
1083         if (hdl != NULL) {
1084                 zp = sa_get_userdata(hdl);
1085
1086
1087                 /*
1088                  * Since "SA" does immediate eviction we
1089                  * should never find a sa handle that doesn't
1090                  * know about the znode.
1091                  */
1092
1093                 ASSERT3P(zp, !=, NULL);
1094
1095                 mutex_enter(&zp->z_lock);
1096                 ASSERT3U(zp->z_id, ==, obj_num);
1097                 /*
1098                  * If igrab() returns NULL the VFS has independently
1099                  * determined the inode should be evicted and has
1100                  * called iput_final() to start the eviction process.
1101                  * The SA handle is still valid but because the VFS
1102                  * requires that the eviction succeed we must drop
1103                  * our locks and references to allow the eviction to
1104                  * complete.  The zfs_zget() may then be retried.
1105                  *
1106                  * This unlikely case could be optimized by registering
1107                  * a sops->drop_inode() callback.  The callback would
1108                  * need to detect the active SA hold thereby informing
1109                  * the VFS that this inode should not be evicted.
1110                  */
1111                 if (igrab(ZTOI(zp)) == NULL) {
1112                         mutex_exit(&zp->z_lock);
1113                         sa_buf_rele(db, NULL);
1114                         zfs_znode_hold_exit(zfsvfs, zh);
1115                         /* inode might need this to finish evict */
1116                         cond_resched();
1117                         goto again;
1118                 }
1119                 *zpp = zp;
1120                 err = 0;
1121                 mutex_exit(&zp->z_lock);
1122                 sa_buf_rele(db, NULL);
1123                 zfs_znode_hold_exit(zfsvfs, zh);
1124                 return (err);
1125         }
1126
1127         /*
1128          * Not found create new znode/vnode but only if file exists.
1129          *
1130          * There is a small window where zfs_vget() could
1131          * find this object while a file create is still in
1132          * progress.  This is checked for in zfs_znode_alloc()
1133          *
1134          * if zfs_znode_alloc() fails it will drop the hold on the
1135          * bonus buffer.
1136          */
1137         zp = zfs_znode_alloc(zfsvfs, db, doi.doi_data_block_size,
1138             doi.doi_bonus_type, obj_num, NULL);
1139         if (zp == NULL) {
1140                 err = SET_ERROR(ENOENT);
1141         } else {
1142                 *zpp = zp;
1143         }
1144         zfs_znode_hold_exit(zfsvfs, zh);
1145         return (err);
1146 }
1147
1148 int
1149 zfs_rezget(znode_t *zp)
1150 {
1151         zfsvfs_t *zfsvfs = ZTOZSB(zp);
1152         dmu_object_info_t doi;
1153         dmu_buf_t *db;
1154         uint64_t obj_num = zp->z_id;
1155         uint64_t mode;
1156         uint64_t links;
1157         sa_bulk_attr_t bulk[10];
1158         int err;
1159         int count = 0;
1160         uint64_t gen;
1161         uint64_t z_uid, z_gid;
1162         uint64_t atime[2], mtime[2], ctime[2];
1163         uint64_t projid = ZFS_DEFAULT_PROJID;
1164         znode_hold_t *zh;
1165
1166         /*
1167          * skip ctldir, otherwise they will always get invalidated. This will
1168          * cause funny behaviour for the mounted snapdirs. Especially for
1169          * Linux >= 3.18, d_invalidate will detach the mountpoint and prevent
1170          * anyone automount it again as long as someone is still using the
1171          * detached mount.
1172          */
1173         if (zp->z_is_ctldir)
1174                 return (0);
1175
1176         zh = zfs_znode_hold_enter(zfsvfs, obj_num);
1177
1178         mutex_enter(&zp->z_acl_lock);
1179         if (zp->z_acl_cached) {
1180                 zfs_acl_free(zp->z_acl_cached);
1181                 zp->z_acl_cached = NULL;
1182         }
1183         mutex_exit(&zp->z_acl_lock);
1184
1185         rw_enter(&zp->z_xattr_lock, RW_WRITER);
1186         if (zp->z_xattr_cached) {
1187                 nvlist_free(zp->z_xattr_cached);
1188                 zp->z_xattr_cached = NULL;
1189         }
1190         rw_exit(&zp->z_xattr_lock);
1191
1192         ASSERT(zp->z_sa_hdl == NULL);
1193         err = sa_buf_hold(zfsvfs->z_os, obj_num, NULL, &db);
1194         if (err) {
1195                 zfs_znode_hold_exit(zfsvfs, zh);
1196                 return (err);
1197         }
1198
1199         dmu_object_info_from_db(db, &doi);
1200         if (doi.doi_bonus_type != DMU_OT_SA &&
1201             (doi.doi_bonus_type != DMU_OT_ZNODE ||
1202             (doi.doi_bonus_type == DMU_OT_ZNODE &&
1203             doi.doi_bonus_size < sizeof (znode_phys_t)))) {
1204                 sa_buf_rele(db, NULL);
1205                 zfs_znode_hold_exit(zfsvfs, zh);
1206                 return (SET_ERROR(EINVAL));
1207         }
1208
1209         zfs_znode_sa_init(zfsvfs, zp, db, doi.doi_bonus_type, NULL);
1210
1211         /* reload cached values */
1212         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zfsvfs), NULL,
1213             &gen, sizeof (gen));
1214         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
1215             &zp->z_size, sizeof (zp->z_size));
1216         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
1217             &links, sizeof (links));
1218         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
1219             &zp->z_pflags, sizeof (zp->z_pflags));
1220         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
1221             &z_uid, sizeof (z_uid));
1222         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
1223             &z_gid, sizeof (z_gid));
1224         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
1225             &mode, sizeof (mode));
1226         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
1227             &atime, 16);
1228         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
1229             &mtime, 16);
1230         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
1231             &ctime, 16);
1232
1233         if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) {
1234                 zfs_znode_dmu_fini(zp);
1235                 zfs_znode_hold_exit(zfsvfs, zh);
1236                 return (SET_ERROR(EIO));
1237         }
1238
1239         if (dmu_objset_projectquota_enabled(zfsvfs->z_os)) {
1240                 err = sa_lookup(zp->z_sa_hdl, SA_ZPL_PROJID(zfsvfs),
1241                     &projid, 8);
1242                 if (err != 0 && err != ENOENT) {
1243                         zfs_znode_dmu_fini(zp);
1244                         zfs_znode_hold_exit(zfsvfs, zh);
1245                         return (SET_ERROR(err));
1246                 }
1247         }
1248
1249         zp->z_projid = projid;
1250         zp->z_mode = ZTOI(zp)->i_mode = mode;
1251         zfs_uid_write(ZTOI(zp), z_uid);
1252         zfs_gid_write(ZTOI(zp), z_gid);
1253
1254         ZFS_TIME_DECODE(&ZTOI(zp)->i_atime, atime);
1255         ZFS_TIME_DECODE(&ZTOI(zp)->i_mtime, mtime);
1256         ZFS_TIME_DECODE(&ZTOI(zp)->i_ctime, ctime);
1257
1258         if (gen != ZTOI(zp)->i_generation) {
1259                 zfs_znode_dmu_fini(zp);
1260                 zfs_znode_hold_exit(zfsvfs, zh);
1261                 return (SET_ERROR(EIO));
1262         }
1263
1264         set_nlink(ZTOI(zp), (uint32_t)links);
1265         zfs_set_inode_flags(zp, ZTOI(zp));
1266
1267         zp->z_blksz = doi.doi_data_block_size;
1268         zp->z_atime_dirty = 0;
1269         zfs_inode_update(zp);
1270
1271         /*
1272          * If the file has zero links, then it has been unlinked on the send
1273          * side and it must be in the received unlinked set.
1274          * We call zfs_znode_dmu_fini() now to prevent any accesses to the
1275          * stale data and to prevent automatical removal of the file in
1276          * zfs_zinactive().  The file will be removed either when it is removed
1277          * on the send side and the next incremental stream is received or
1278          * when the unlinked set gets processed.
1279          */
1280         zp->z_unlinked = (ZTOI(zp)->i_nlink == 0);
1281         if (zp->z_unlinked)
1282                 zfs_znode_dmu_fini(zp);
1283
1284         zfs_znode_hold_exit(zfsvfs, zh);
1285
1286         return (0);
1287 }
1288
1289 void
1290 zfs_znode_delete(znode_t *zp, dmu_tx_t *tx)
1291 {
1292         zfsvfs_t *zfsvfs = ZTOZSB(zp);
1293         objset_t *os = zfsvfs->z_os;
1294         uint64_t obj = zp->z_id;
1295         uint64_t acl_obj = zfs_external_acl(zp);
1296         znode_hold_t *zh;
1297
1298         zh = zfs_znode_hold_enter(zfsvfs, obj);
1299         if (acl_obj) {
1300                 VERIFY(!zp->z_is_sa);
1301                 VERIFY(0 == dmu_object_free(os, acl_obj, tx));
1302         }
1303         VERIFY(0 == dmu_object_free(os, obj, tx));
1304         zfs_znode_dmu_fini(zp);
1305         zfs_znode_hold_exit(zfsvfs, zh);
1306 }
1307
1308 void
1309 zfs_zinactive(znode_t *zp)
1310 {
1311         zfsvfs_t *zfsvfs = ZTOZSB(zp);
1312         uint64_t z_id = zp->z_id;
1313         znode_hold_t *zh;
1314
1315         ASSERT(zp->z_sa_hdl);
1316
1317         /*
1318          * Don't allow a zfs_zget() while were trying to release this znode.
1319          */
1320         zh = zfs_znode_hold_enter(zfsvfs, z_id);
1321
1322         mutex_enter(&zp->z_lock);
1323
1324         /*
1325          * If this was the last reference to a file with no links, remove
1326          * the file from the file system unless the file system is mounted
1327          * read-only.  That can happen, for example, if the file system was
1328          * originally read-write, the file was opened, then unlinked and
1329          * the file system was made read-only before the file was finally
1330          * closed.  The file will remain in the unlinked set.
1331          */
1332         if (zp->z_unlinked) {
1333                 ASSERT(!zfsvfs->z_issnap);
1334                 if (!zfs_is_readonly(zfsvfs) && !zfs_unlink_suspend_progress) {
1335                         mutex_exit(&zp->z_lock);
1336                         zfs_znode_hold_exit(zfsvfs, zh);
1337                         zfs_rmnode(zp);
1338                         return;
1339                 }
1340         }
1341
1342         mutex_exit(&zp->z_lock);
1343         zfs_znode_dmu_fini(zp);
1344
1345         zfs_znode_hold_exit(zfsvfs, zh);
1346 }
1347
1348 #if defined(HAVE_INODE_TIMESPEC64_TIMES)
1349 #define zfs_compare_timespec timespec64_compare
1350 #else
1351 #define zfs_compare_timespec timespec_compare
1352 #endif
1353
1354 /*
1355  * Determine whether the znode's atime must be updated.  The logic mostly
1356  * duplicates the Linux kernel's relatime_need_update() functionality.
1357  * This function is only called if the underlying filesystem actually has
1358  * atime updates enabled.
1359  */
1360 boolean_t
1361 zfs_relatime_need_update(const struct inode *ip)
1362 {
1363         inode_timespec_t now;
1364
1365         gethrestime(&now);
1366         /*
1367          * In relatime mode, only update the atime if the previous atime
1368          * is earlier than either the ctime or mtime or if at least a day
1369          * has passed since the last update of atime.
1370          */
1371         if (zfs_compare_timespec(&ip->i_mtime, &ip->i_atime) >= 0)
1372                 return (B_TRUE);
1373
1374         if (zfs_compare_timespec(&ip->i_ctime, &ip->i_atime) >= 0)
1375                 return (B_TRUE);
1376
1377         if ((hrtime_t)now.tv_sec - (hrtime_t)ip->i_atime.tv_sec >= 24*60*60)
1378                 return (B_TRUE);
1379
1380         return (B_FALSE);
1381 }
1382
1383 /*
1384  * Prepare to update znode time stamps.
1385  *
1386  *      IN:     zp      - znode requiring timestamp update
1387  *              flag    - ATTR_MTIME, ATTR_CTIME flags
1388  *
1389  *      OUT:    zp      - z_seq
1390  *              mtime   - new mtime
1391  *              ctime   - new ctime
1392  *
1393  *      Note: We don't update atime here, because we rely on Linux VFS to do
1394  *      atime updating.
1395  */
1396 void
1397 zfs_tstamp_update_setup(znode_t *zp, uint_t flag, uint64_t mtime[2],
1398     uint64_t ctime[2])
1399 {
1400         inode_timespec_t now;
1401
1402         gethrestime(&now);
1403
1404         zp->z_seq++;
1405
1406         if (flag & ATTR_MTIME) {
1407                 ZFS_TIME_ENCODE(&now, mtime);
1408                 ZFS_TIME_DECODE(&(ZTOI(zp)->i_mtime), mtime);
1409                 if (ZTOZSB(zp)->z_use_fuids) {
1410                         zp->z_pflags |= (ZFS_ARCHIVE |
1411                             ZFS_AV_MODIFIED);
1412                 }
1413         }
1414
1415         if (flag & ATTR_CTIME) {
1416                 ZFS_TIME_ENCODE(&now, ctime);
1417                 ZFS_TIME_DECODE(&(ZTOI(zp)->i_ctime), ctime);
1418                 if (ZTOZSB(zp)->z_use_fuids)
1419                         zp->z_pflags |= ZFS_ARCHIVE;
1420         }
1421 }
1422
1423 /*
1424  * Grow the block size for a file.
1425  *
1426  *      IN:     zp      - znode of file to free data in.
1427  *              size    - requested block size
1428  *              tx      - open transaction.
1429  *
1430  * NOTE: this function assumes that the znode is write locked.
1431  */
1432 void
1433 zfs_grow_blocksize(znode_t *zp, uint64_t size, dmu_tx_t *tx)
1434 {
1435         int             error;
1436         u_longlong_t    dummy;
1437
1438         if (size <= zp->z_blksz)
1439                 return;
1440         /*
1441          * If the file size is already greater than the current blocksize,
1442          * we will not grow.  If there is more than one block in a file,
1443          * the blocksize cannot change.
1444          */
1445         if (zp->z_blksz && zp->z_size > zp->z_blksz)
1446                 return;
1447
1448         error = dmu_object_set_blocksize(ZTOZSB(zp)->z_os, zp->z_id,
1449             size, 0, tx);
1450
1451         if (error == ENOTSUP)
1452                 return;
1453         ASSERT0(error);
1454
1455         /* What blocksize did we actually get? */
1456         dmu_object_size_from_db(sa_get_db(zp->z_sa_hdl), &zp->z_blksz, &dummy);
1457 }
1458
1459 /*
1460  * Increase the file length
1461  *
1462  *      IN:     zp      - znode of file to free data in.
1463  *              end     - new end-of-file
1464  *
1465  *      RETURN: 0 on success, error code on failure
1466  */
1467 static int
1468 zfs_extend(znode_t *zp, uint64_t end)
1469 {
1470         zfsvfs_t *zfsvfs = ZTOZSB(zp);
1471         dmu_tx_t *tx;
1472         locked_range_t *lr;
1473         uint64_t newblksz;
1474         int error;
1475
1476         /*
1477          * We will change zp_size, lock the whole file.
1478          */
1479         lr = rangelock_enter(&zp->z_rangelock, 0, UINT64_MAX, RL_WRITER);
1480
1481         /*
1482          * Nothing to do if file already at desired length.
1483          */
1484         if (end <= zp->z_size) {
1485                 rangelock_exit(lr);
1486                 return (0);
1487         }
1488         tx = dmu_tx_create(zfsvfs->z_os);
1489         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1490         zfs_sa_upgrade_txholds(tx, zp);
1491         if (end > zp->z_blksz &&
1492             (!ISP2(zp->z_blksz) || zp->z_blksz < zfsvfs->z_max_blksz)) {
1493                 /*
1494                  * We are growing the file past the current block size.
1495                  */
1496                 if (zp->z_blksz > ZTOZSB(zp)->z_max_blksz) {
1497                         /*
1498                          * File's blocksize is already larger than the
1499                          * "recordsize" property.  Only let it grow to
1500                          * the next power of 2.
1501                          */
1502                         ASSERT(!ISP2(zp->z_blksz));
1503                         newblksz = MIN(end, 1 << highbit64(zp->z_blksz));
1504                 } else {
1505                         newblksz = MIN(end, ZTOZSB(zp)->z_max_blksz);
1506                 }
1507                 dmu_tx_hold_write(tx, zp->z_id, 0, newblksz);
1508         } else {
1509                 newblksz = 0;
1510         }
1511
1512         error = dmu_tx_assign(tx, TXG_WAIT);
1513         if (error) {
1514                 dmu_tx_abort(tx);
1515                 rangelock_exit(lr);
1516                 return (error);
1517         }
1518
1519         if (newblksz)
1520                 zfs_grow_blocksize(zp, newblksz, tx);
1521
1522         zp->z_size = end;
1523
1524         VERIFY(0 == sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(ZTOZSB(zp)),
1525             &zp->z_size, sizeof (zp->z_size), tx));
1526
1527         rangelock_exit(lr);
1528
1529         dmu_tx_commit(tx);
1530
1531         return (0);
1532 }
1533
1534 /*
1535  * zfs_zero_partial_page - Modeled after update_pages() but
1536  * with different arguments and semantics for use by zfs_freesp().
1537  *
1538  * Zeroes a piece of a single page cache entry for zp at offset
1539  * start and length len.
1540  *
1541  * Caller must acquire a range lock on the file for the region
1542  * being zeroed in order that the ARC and page cache stay in sync.
1543  */
1544 static void
1545 zfs_zero_partial_page(znode_t *zp, uint64_t start, uint64_t len)
1546 {
1547         struct address_space *mp = ZTOI(zp)->i_mapping;
1548         struct page *pp;
1549         int64_t off;
1550         void *pb;
1551
1552         ASSERT((start & PAGE_MASK) == ((start + len - 1) & PAGE_MASK));
1553
1554         off = start & (PAGE_SIZE - 1);
1555         start &= PAGE_MASK;
1556
1557         pp = find_lock_page(mp, start >> PAGE_SHIFT);
1558         if (pp) {
1559                 if (mapping_writably_mapped(mp))
1560                         flush_dcache_page(pp);
1561
1562                 pb = kmap(pp);
1563                 bzero(pb + off, len);
1564                 kunmap(pp);
1565
1566                 if (mapping_writably_mapped(mp))
1567                         flush_dcache_page(pp);
1568
1569                 mark_page_accessed(pp);
1570                 SetPageUptodate(pp);
1571                 ClearPageError(pp);
1572                 unlock_page(pp);
1573                 put_page(pp);
1574         }
1575 }
1576
1577 /*
1578  * Free space in a file.
1579  *
1580  *      IN:     zp      - znode of file to free data in.
1581  *              off     - start of section to free.
1582  *              len     - length of section to free.
1583  *
1584  *      RETURN: 0 on success, error code on failure
1585  */
1586 static int
1587 zfs_free_range(znode_t *zp, uint64_t off, uint64_t len)
1588 {
1589         zfsvfs_t *zfsvfs = ZTOZSB(zp);
1590         locked_range_t *lr;
1591         int error;
1592
1593         /*
1594          * Lock the range being freed.
1595          */
1596         lr = rangelock_enter(&zp->z_rangelock, off, len, RL_WRITER);
1597
1598         /*
1599          * Nothing to do if file already at desired length.
1600          */
1601         if (off >= zp->z_size) {
1602                 rangelock_exit(lr);
1603                 return (0);
1604         }
1605
1606         if (off + len > zp->z_size)
1607                 len = zp->z_size - off;
1608
1609         error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, off, len);
1610
1611         /*
1612          * Zero partial page cache entries.  This must be done under a
1613          * range lock in order to keep the ARC and page cache in sync.
1614          */
1615         if (zp->z_is_mapped) {
1616                 loff_t first_page, last_page, page_len;
1617                 loff_t first_page_offset, last_page_offset;
1618
1619                 /* first possible full page in hole */
1620                 first_page = (off + PAGE_SIZE - 1) >> PAGE_SHIFT;
1621                 /* last page of hole */
1622                 last_page = (off + len) >> PAGE_SHIFT;
1623
1624                 /* offset of first_page */
1625                 first_page_offset = first_page << PAGE_SHIFT;
1626                 /* offset of last_page */
1627                 last_page_offset = last_page << PAGE_SHIFT;
1628
1629                 /* truncate whole pages */
1630                 if (last_page_offset > first_page_offset) {
1631                         truncate_inode_pages_range(ZTOI(zp)->i_mapping,
1632                             first_page_offset, last_page_offset - 1);
1633                 }
1634
1635                 /* truncate sub-page ranges */
1636                 if (first_page > last_page) {
1637                         /* entire punched area within a single page */
1638                         zfs_zero_partial_page(zp, off, len);
1639                 } else {
1640                         /* beginning of punched area at the end of a page */
1641                         page_len  = first_page_offset - off;
1642                         if (page_len > 0)
1643                                 zfs_zero_partial_page(zp, off, page_len);
1644
1645                         /* end of punched area at the beginning of a page */
1646                         page_len = off + len - last_page_offset;
1647                         if (page_len > 0)
1648                                 zfs_zero_partial_page(zp, last_page_offset,
1649                                     page_len);
1650                 }
1651         }
1652         rangelock_exit(lr);
1653
1654         return (error);
1655 }
1656
1657 /*
1658  * Truncate a file
1659  *
1660  *      IN:     zp      - znode of file to free data in.
1661  *              end     - new end-of-file.
1662  *
1663  *      RETURN: 0 on success, error code on failure
1664  */
1665 static int
1666 zfs_trunc(znode_t *zp, uint64_t end)
1667 {
1668         zfsvfs_t *zfsvfs = ZTOZSB(zp);
1669         dmu_tx_t *tx;
1670         locked_range_t *lr;
1671         int error;
1672         sa_bulk_attr_t bulk[2];
1673         int count = 0;
1674
1675         /*
1676          * We will change zp_size, lock the whole file.
1677          */
1678         lr = rangelock_enter(&zp->z_rangelock, 0, UINT64_MAX, RL_WRITER);
1679
1680         /*
1681          * Nothing to do if file already at desired length.
1682          */
1683         if (end >= zp->z_size) {
1684                 rangelock_exit(lr);
1685                 return (0);
1686         }
1687
1688         error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, end,
1689             DMU_OBJECT_END);
1690         if (error) {
1691                 rangelock_exit(lr);
1692                 return (error);
1693         }
1694         tx = dmu_tx_create(zfsvfs->z_os);
1695         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1696         zfs_sa_upgrade_txholds(tx, zp);
1697         dmu_tx_mark_netfree(tx);
1698         error = dmu_tx_assign(tx, TXG_WAIT);
1699         if (error) {
1700                 dmu_tx_abort(tx);
1701                 rangelock_exit(lr);
1702                 return (error);
1703         }
1704
1705         zp->z_size = end;
1706         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs),
1707             NULL, &zp->z_size, sizeof (zp->z_size));
1708
1709         if (end == 0) {
1710                 zp->z_pflags &= ~ZFS_SPARSE;
1711                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1712                     NULL, &zp->z_pflags, 8);
1713         }
1714         VERIFY(sa_bulk_update(zp->z_sa_hdl, bulk, count, tx) == 0);
1715
1716         dmu_tx_commit(tx);
1717         rangelock_exit(lr);
1718
1719         return (0);
1720 }
1721
1722 /*
1723  * Free space in a file
1724  *
1725  *      IN:     zp      - znode of file to free data in.
1726  *              off     - start of range
1727  *              len     - end of range (0 => EOF)
1728  *              flag    - current file open mode flags.
1729  *              log     - TRUE if this action should be logged
1730  *
1731  *      RETURN: 0 on success, error code on failure
1732  */
1733 int
1734 zfs_freesp(znode_t *zp, uint64_t off, uint64_t len, int flag, boolean_t log)
1735 {
1736         dmu_tx_t *tx;
1737         zfsvfs_t *zfsvfs = ZTOZSB(zp);
1738         zilog_t *zilog = zfsvfs->z_log;
1739         uint64_t mode;
1740         uint64_t mtime[2], ctime[2];
1741         sa_bulk_attr_t bulk[3];
1742         int count = 0;
1743         int error;
1744
1745         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs), &mode,
1746             sizeof (mode))) != 0)
1747                 return (error);
1748
1749         if (off > zp->z_size) {
1750                 error =  zfs_extend(zp, off+len);
1751                 if (error == 0 && log)
1752                         goto log;
1753                 goto out;
1754         }
1755
1756         if (len == 0) {
1757                 error = zfs_trunc(zp, off);
1758         } else {
1759                 if ((error = zfs_free_range(zp, off, len)) == 0 &&
1760                     off + len > zp->z_size)
1761                         error = zfs_extend(zp, off+len);
1762         }
1763         if (error || !log)
1764                 goto out;
1765 log:
1766         tx = dmu_tx_create(zfsvfs->z_os);
1767         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1768         zfs_sa_upgrade_txholds(tx, zp);
1769         error = dmu_tx_assign(tx, TXG_WAIT);
1770         if (error) {
1771                 dmu_tx_abort(tx);
1772                 goto out;
1773         }
1774
1775         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, mtime, 16);
1776         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, ctime, 16);
1777         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1778             NULL, &zp->z_pflags, 8);
1779         zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
1780         error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1781         ASSERT(error == 0);
1782
1783         zfs_log_truncate(zilog, tx, TX_TRUNCATE, zp, off, len);
1784
1785         dmu_tx_commit(tx);
1786
1787         zfs_inode_update(zp);
1788         error = 0;
1789
1790 out:
1791         /*
1792          * Truncate the page cache - for file truncate operations, use
1793          * the purpose-built API for truncations.  For punching operations,
1794          * the truncation is handled under a range lock in zfs_free_range.
1795          */
1796         if (len == 0)
1797                 truncate_setsize(ZTOI(zp), off);
1798         return (error);
1799 }
1800
1801 void
1802 zfs_create_fs(objset_t *os, cred_t *cr, nvlist_t *zplprops, dmu_tx_t *tx)
1803 {
1804         struct super_block *sb;
1805         zfsvfs_t        *zfsvfs;
1806         uint64_t        moid, obj, sa_obj, version;
1807         uint64_t        sense = ZFS_CASE_SENSITIVE;
1808         uint64_t        norm = 0;
1809         nvpair_t        *elem;
1810         int             size;
1811         int             error;
1812         int             i;
1813         znode_t         *rootzp = NULL;
1814         vattr_t         vattr;
1815         znode_t         *zp;
1816         zfs_acl_ids_t   acl_ids;
1817
1818         /*
1819          * First attempt to create master node.
1820          */
1821         /*
1822          * In an empty objset, there are no blocks to read and thus
1823          * there can be no i/o errors (which we assert below).
1824          */
1825         moid = MASTER_NODE_OBJ;
1826         error = zap_create_claim(os, moid, DMU_OT_MASTER_NODE,
1827             DMU_OT_NONE, 0, tx);
1828         ASSERT(error == 0);
1829
1830         /*
1831          * Set starting attributes.
1832          */
1833         version = zfs_zpl_version_map(spa_version(dmu_objset_spa(os)));
1834         elem = NULL;
1835         while ((elem = nvlist_next_nvpair(zplprops, elem)) != NULL) {
1836                 /* For the moment we expect all zpl props to be uint64_ts */
1837                 uint64_t val;
1838                 char *name;
1839
1840                 ASSERT(nvpair_type(elem) == DATA_TYPE_UINT64);
1841                 VERIFY(nvpair_value_uint64(elem, &val) == 0);
1842                 name = nvpair_name(elem);
1843                 if (strcmp(name, zfs_prop_to_name(ZFS_PROP_VERSION)) == 0) {
1844                         if (val < version)
1845                                 version = val;
1846                 } else {
1847                         error = zap_update(os, moid, name, 8, 1, &val, tx);
1848                 }
1849                 ASSERT(error == 0);
1850                 if (strcmp(name, zfs_prop_to_name(ZFS_PROP_NORMALIZE)) == 0)
1851                         norm = val;
1852                 else if (strcmp(name, zfs_prop_to_name(ZFS_PROP_CASE)) == 0)
1853                         sense = val;
1854         }
1855         ASSERT(version != 0);
1856         error = zap_update(os, moid, ZPL_VERSION_STR, 8, 1, &version, tx);
1857
1858         /*
1859          * Create zap object used for SA attribute registration
1860          */
1861
1862         if (version >= ZPL_VERSION_SA) {
1863                 sa_obj = zap_create(os, DMU_OT_SA_MASTER_NODE,
1864                     DMU_OT_NONE, 0, tx);
1865                 error = zap_add(os, moid, ZFS_SA_ATTRS, 8, 1, &sa_obj, tx);
1866                 ASSERT(error == 0);
1867         } else {
1868                 sa_obj = 0;
1869         }
1870         /*
1871          * Create a delete queue.
1872          */
1873         obj = zap_create(os, DMU_OT_UNLINKED_SET, DMU_OT_NONE, 0, tx);
1874
1875         error = zap_add(os, moid, ZFS_UNLINKED_SET, 8, 1, &obj, tx);
1876         ASSERT(error == 0);
1877
1878         /*
1879          * Create root znode.  Create minimal znode/inode/zfsvfs/sb
1880          * to allow zfs_mknode to work.
1881          */
1882         vattr.va_mask = ATTR_MODE|ATTR_UID|ATTR_GID;
1883         vattr.va_mode = S_IFDIR|0755;
1884         vattr.va_uid = crgetuid(cr);
1885         vattr.va_gid = crgetgid(cr);
1886
1887         rootzp = kmem_cache_alloc(znode_cache, KM_SLEEP);
1888         rootzp->z_moved = 0;
1889         rootzp->z_unlinked = 0;
1890         rootzp->z_atime_dirty = 0;
1891         rootzp->z_is_sa = USE_SA(version, os);
1892         rootzp->z_pflags = 0;
1893
1894         zfsvfs = kmem_zalloc(sizeof (zfsvfs_t), KM_SLEEP);
1895         zfsvfs->z_os = os;
1896         zfsvfs->z_parent = zfsvfs;
1897         zfsvfs->z_version = version;
1898         zfsvfs->z_use_fuids = USE_FUIDS(version, os);
1899         zfsvfs->z_use_sa = USE_SA(version, os);
1900         zfsvfs->z_norm = norm;
1901
1902         sb = kmem_zalloc(sizeof (struct super_block), KM_SLEEP);
1903         sb->s_fs_info = zfsvfs;
1904
1905         ZTOI(rootzp)->i_sb = sb;
1906
1907         error = sa_setup(os, sa_obj, zfs_attr_table, ZPL_END,
1908             &zfsvfs->z_attr_table);
1909
1910         ASSERT(error == 0);
1911
1912         /*
1913          * Fold case on file systems that are always or sometimes case
1914          * insensitive.
1915          */
1916         if (sense == ZFS_CASE_INSENSITIVE || sense == ZFS_CASE_MIXED)
1917                 zfsvfs->z_norm |= U8_TEXTPREP_TOUPPER;
1918
1919         mutex_init(&zfsvfs->z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
1920         list_create(&zfsvfs->z_all_znodes, sizeof (znode_t),
1921             offsetof(znode_t, z_link_node));
1922
1923         size = MIN(1 << (highbit64(zfs_object_mutex_size)-1), ZFS_OBJ_MTX_MAX);
1924         zfsvfs->z_hold_size = size;
1925         zfsvfs->z_hold_trees = vmem_zalloc(sizeof (avl_tree_t) * size,
1926             KM_SLEEP);
1927         zfsvfs->z_hold_locks = vmem_zalloc(sizeof (kmutex_t) * size, KM_SLEEP);
1928         for (i = 0; i != size; i++) {
1929                 avl_create(&zfsvfs->z_hold_trees[i], zfs_znode_hold_compare,
1930                     sizeof (znode_hold_t), offsetof(znode_hold_t, zh_node));
1931                 mutex_init(&zfsvfs->z_hold_locks[i], NULL, MUTEX_DEFAULT, NULL);
1932         }
1933
1934         VERIFY(0 == zfs_acl_ids_create(rootzp, IS_ROOT_NODE, &vattr,
1935             cr, NULL, &acl_ids));
1936         zfs_mknode(rootzp, &vattr, tx, cr, IS_ROOT_NODE, &zp, &acl_ids);
1937         ASSERT3P(zp, ==, rootzp);
1938         error = zap_add(os, moid, ZFS_ROOT_OBJ, 8, 1, &rootzp->z_id, tx);
1939         ASSERT(error == 0);
1940         zfs_acl_ids_free(&acl_ids);
1941
1942         atomic_set(&ZTOI(rootzp)->i_count, 0);
1943         sa_handle_destroy(rootzp->z_sa_hdl);
1944         kmem_cache_free(znode_cache, rootzp);
1945
1946         for (i = 0; i != size; i++) {
1947                 avl_destroy(&zfsvfs->z_hold_trees[i]);
1948                 mutex_destroy(&zfsvfs->z_hold_locks[i]);
1949         }
1950
1951         mutex_destroy(&zfsvfs->z_znodes_lock);
1952
1953         vmem_free(zfsvfs->z_hold_trees, sizeof (avl_tree_t) * size);
1954         vmem_free(zfsvfs->z_hold_locks, sizeof (kmutex_t) * size);
1955         kmem_free(sb, sizeof (struct super_block));
1956         kmem_free(zfsvfs, sizeof (zfsvfs_t));
1957 }
1958 #endif /* _KERNEL */
1959
1960 static int
1961 zfs_sa_setup(objset_t *osp, sa_attr_type_t **sa_table)
1962 {
1963         uint64_t sa_obj = 0;
1964         int error;
1965
1966         error = zap_lookup(osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS, 8, 1, &sa_obj);
1967         if (error != 0 && error != ENOENT)
1968                 return (error);
1969
1970         error = sa_setup(osp, sa_obj, zfs_attr_table, ZPL_END, sa_table);
1971         return (error);
1972 }
1973
1974 static int
1975 zfs_grab_sa_handle(objset_t *osp, uint64_t obj, sa_handle_t **hdlp,
1976     dmu_buf_t **db, void *tag)
1977 {
1978         dmu_object_info_t doi;
1979         int error;
1980
1981         if ((error = sa_buf_hold(osp, obj, tag, db)) != 0)
1982                 return (error);
1983
1984         dmu_object_info_from_db(*db, &doi);
1985         if ((doi.doi_bonus_type != DMU_OT_SA &&
1986             doi.doi_bonus_type != DMU_OT_ZNODE) ||
1987             (doi.doi_bonus_type == DMU_OT_ZNODE &&
1988             doi.doi_bonus_size < sizeof (znode_phys_t))) {
1989                 sa_buf_rele(*db, tag);
1990                 return (SET_ERROR(ENOTSUP));
1991         }
1992
1993         error = sa_handle_get(osp, obj, NULL, SA_HDL_PRIVATE, hdlp);
1994         if (error != 0) {
1995                 sa_buf_rele(*db, tag);
1996                 return (error);
1997         }
1998
1999         return (0);
2000 }
2001
2002 void
2003 zfs_release_sa_handle(sa_handle_t *hdl, dmu_buf_t *db, void *tag)
2004 {
2005         sa_handle_destroy(hdl);
2006         sa_buf_rele(db, tag);
2007 }
2008
2009 /*
2010  * Given an object number, return its parent object number and whether
2011  * or not the object is an extended attribute directory.
2012  */
2013 static int
2014 zfs_obj_to_pobj(objset_t *osp, sa_handle_t *hdl, sa_attr_type_t *sa_table,
2015     uint64_t *pobjp, int *is_xattrdir)
2016 {
2017         uint64_t parent;
2018         uint64_t pflags;
2019         uint64_t mode;
2020         uint64_t parent_mode;
2021         sa_bulk_attr_t bulk[3];
2022         sa_handle_t *sa_hdl;
2023         dmu_buf_t *sa_db;
2024         int count = 0;
2025         int error;
2026
2027         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_PARENT], NULL,
2028             &parent, sizeof (parent));
2029         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_FLAGS], NULL,
2030             &pflags, sizeof (pflags));
2031         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_MODE], NULL,
2032             &mode, sizeof (mode));
2033
2034         if ((error = sa_bulk_lookup(hdl, bulk, count)) != 0)
2035                 return (error);
2036
2037         /*
2038          * When a link is removed its parent pointer is not changed and will
2039          * be invalid.  There are two cases where a link is removed but the
2040          * file stays around, when it goes to the delete queue and when there
2041          * are additional links.
2042          */
2043         error = zfs_grab_sa_handle(osp, parent, &sa_hdl, &sa_db, FTAG);
2044         if (error != 0)
2045                 return (error);
2046
2047         error = sa_lookup(sa_hdl, ZPL_MODE, &parent_mode, sizeof (parent_mode));
2048         zfs_release_sa_handle(sa_hdl, sa_db, FTAG);
2049         if (error != 0)
2050                 return (error);
2051
2052         *is_xattrdir = ((pflags & ZFS_XATTR) != 0) && S_ISDIR(mode);
2053
2054         /*
2055          * Extended attributes can be applied to files, directories, etc.
2056          * Otherwise the parent must be a directory.
2057          */
2058         if (!*is_xattrdir && !S_ISDIR(parent_mode))
2059                 return (SET_ERROR(EINVAL));
2060
2061         *pobjp = parent;
2062
2063         return (0);
2064 }
2065
2066 /*
2067  * Given an object number, return some zpl level statistics
2068  */
2069 static int
2070 zfs_obj_to_stats_impl(sa_handle_t *hdl, sa_attr_type_t *sa_table,
2071     zfs_stat_t *sb)
2072 {
2073         sa_bulk_attr_t bulk[4];
2074         int count = 0;
2075
2076         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_MODE], NULL,
2077             &sb->zs_mode, sizeof (sb->zs_mode));
2078         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_GEN], NULL,
2079             &sb->zs_gen, sizeof (sb->zs_gen));
2080         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_LINKS], NULL,
2081             &sb->zs_links, sizeof (sb->zs_links));
2082         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_CTIME], NULL,
2083             &sb->zs_ctime, sizeof (sb->zs_ctime));
2084
2085         return (sa_bulk_lookup(hdl, bulk, count));
2086 }
2087
2088 static int
2089 zfs_obj_to_path_impl(objset_t *osp, uint64_t obj, sa_handle_t *hdl,
2090     sa_attr_type_t *sa_table, char *buf, int len)
2091 {
2092         sa_handle_t *sa_hdl;
2093         sa_handle_t *prevhdl = NULL;
2094         dmu_buf_t *prevdb = NULL;
2095         dmu_buf_t *sa_db = NULL;
2096         char *path = buf + len - 1;
2097         int error;
2098
2099         *path = '\0';
2100         sa_hdl = hdl;
2101
2102         uint64_t deleteq_obj;
2103         VERIFY0(zap_lookup(osp, MASTER_NODE_OBJ,
2104             ZFS_UNLINKED_SET, sizeof (uint64_t), 1, &deleteq_obj));
2105         error = zap_lookup_int(osp, deleteq_obj, obj);
2106         if (error == 0) {
2107                 return (ESTALE);
2108         } else if (error != ENOENT) {
2109                 return (error);
2110         }
2111         error = 0;
2112
2113         for (;;) {
2114                 uint64_t pobj = 0;
2115                 char component[MAXNAMELEN + 2];
2116                 size_t complen;
2117                 int is_xattrdir = 0;
2118
2119                 if (prevdb)
2120                         zfs_release_sa_handle(prevhdl, prevdb, FTAG);
2121
2122                 if ((error = zfs_obj_to_pobj(osp, sa_hdl, sa_table, &pobj,
2123                     &is_xattrdir)) != 0)
2124                         break;
2125
2126                 if (pobj == obj) {
2127                         if (path[0] != '/')
2128                                 *--path = '/';
2129                         break;
2130                 }
2131
2132                 component[0] = '/';
2133                 if (is_xattrdir) {
2134                         (void) sprintf(component + 1, "<xattrdir>");
2135                 } else {
2136                         error = zap_value_search(osp, pobj, obj,
2137                             ZFS_DIRENT_OBJ(-1ULL), component + 1);
2138                         if (error != 0)
2139                                 break;
2140                 }
2141
2142                 complen = strlen(component);
2143                 path -= complen;
2144                 ASSERT(path >= buf);
2145                 bcopy(component, path, complen);
2146                 obj = pobj;
2147
2148                 if (sa_hdl != hdl) {
2149                         prevhdl = sa_hdl;
2150                         prevdb = sa_db;
2151                 }
2152                 error = zfs_grab_sa_handle(osp, obj, &sa_hdl, &sa_db, FTAG);
2153                 if (error != 0) {
2154                         sa_hdl = prevhdl;
2155                         sa_db = prevdb;
2156                         break;
2157                 }
2158         }
2159
2160         if (sa_hdl != NULL && sa_hdl != hdl) {
2161                 ASSERT(sa_db != NULL);
2162                 zfs_release_sa_handle(sa_hdl, sa_db, FTAG);
2163         }
2164
2165         if (error == 0)
2166                 (void) memmove(buf, path, buf + len - path);
2167
2168         return (error);
2169 }
2170
2171 int
2172 zfs_obj_to_path(objset_t *osp, uint64_t obj, char *buf, int len)
2173 {
2174         sa_attr_type_t *sa_table;
2175         sa_handle_t *hdl;
2176         dmu_buf_t *db;
2177         int error;
2178
2179         error = zfs_sa_setup(osp, &sa_table);
2180         if (error != 0)
2181                 return (error);
2182
2183         error = zfs_grab_sa_handle(osp, obj, &hdl, &db, FTAG);
2184         if (error != 0)
2185                 return (error);
2186
2187         error = zfs_obj_to_path_impl(osp, obj, hdl, sa_table, buf, len);
2188
2189         zfs_release_sa_handle(hdl, db, FTAG);
2190         return (error);
2191 }
2192
2193 int
2194 zfs_obj_to_stats(objset_t *osp, uint64_t obj, zfs_stat_t *sb,
2195     char *buf, int len)
2196 {
2197         char *path = buf + len - 1;
2198         sa_attr_type_t *sa_table;
2199         sa_handle_t *hdl;
2200         dmu_buf_t *db;
2201         int error;
2202
2203         *path = '\0';
2204
2205         error = zfs_sa_setup(osp, &sa_table);
2206         if (error != 0)
2207                 return (error);
2208
2209         error = zfs_grab_sa_handle(osp, obj, &hdl, &db, FTAG);
2210         if (error != 0)
2211                 return (error);
2212
2213         error = zfs_obj_to_stats_impl(hdl, sa_table, sb);
2214         if (error != 0) {
2215                 zfs_release_sa_handle(hdl, db, FTAG);
2216                 return (error);
2217         }
2218
2219         error = zfs_obj_to_path_impl(osp, obj, hdl, sa_table, buf, len);
2220
2221         zfs_release_sa_handle(hdl, db, FTAG);
2222         return (error);
2223 }
2224
2225 #if defined(_KERNEL)
2226 EXPORT_SYMBOL(zfs_create_fs);
2227 EXPORT_SYMBOL(zfs_obj_to_path);
2228
2229 /* CSTYLED */
2230 module_param(zfs_object_mutex_size, uint, 0644);
2231 MODULE_PARM_DESC(zfs_object_mutex_size, "Size of znode hold array");
2232 module_param(zfs_unlink_suspend_progress, int, 0644);
2233 MODULE_PARM_DESC(zfs_unlink_suspend_progress, "Set to prevent async unlinks "
2234 "(debug - leaks space into the unlinked set)");
2235 #endif