Whamcloud - gitweb
LU-10509 mdd: don't set size attr for DOM file
[fs/lustre-release.git] / lustre / mdd / mdd_object.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/mdd/mdd_object.c
33  *
34  * Lustre Metadata Server (mdd) routines
35  *
36  * Author: Wang Di <wangdi@clusterfs.com>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/module.h>
42 #include <obd.h>
43 #include <obd_class.h>
44 #include <obd_support.h>
45 #include <lprocfs_status.h>
46 /* fid_be_cpu(), fid_cpu_to_be(). */
47 #include <lustre_fid.h>
48 #include <lustre_idmap.h>
49 #include <uapi/linux/lustre/lustre_param.h>
50 #include <lustre_mds.h>
51
52 #include "mdd_internal.h"
53
54 static const struct lu_object_operations mdd_lu_obj_ops;
55
56 struct mdd_object_user {
57         struct list_head        mou_list;       /**< linked off mod_users */
58         int                     mou_flags;      /**< open mode by client */
59         __u64                   mou_uidgid;     /**< uid_gid on client */
60         int                     mou_opencount;  /**< # opened */
61         ktime_t                 mou_deniednext; /**< time of next access denied
62                                                  * notfication
63                                                  */
64 };
65
66 static int mdd_xattr_get(const struct lu_env *env,
67                          struct md_object *obj, struct lu_buf *buf,
68                          const char *name);
69
70 static int mdd_changelog_data_store_by_fid(const struct lu_env *env,
71                                            struct mdd_device *mdd,
72                                            enum changelog_rec_type type,
73                                            int flags, const struct lu_fid *fid,
74                                            const char *xattr_name,
75                                            struct thandle *handle);
76
77 static inline bool has_prefix(const char *str, const char *prefix);
78
79
80 static unsigned int flags_helper(int flags)
81 {
82         unsigned int mflags = 0;
83
84         if (flags & MDS_FMODE_EXEC) {
85                 mflags = MDS_FMODE_EXEC;
86         } else {
87                 if (flags & MDS_FMODE_READ)
88                         mflags = MDS_FMODE_READ;
89                 if (flags &
90                     (MDS_FMODE_WRITE | MDS_OPEN_TRUNC | MDS_OPEN_APPEND))
91                         mflags |= MDS_FMODE_WRITE;
92         }
93
94         return mflags;
95 }
96
97 /** Allocate/init a user and its sub-structures.
98  *
99  * \param flags [IN]
100  * \param uid [IN]
101  * \param gid [IN]
102  * \retval mou [OUT] success valid structure
103  * \retval mou [OUT]
104  */
105 static struct mdd_object_user *mdd_obj_user_alloc(int flags,
106                                                   uid_t uid, gid_t gid)
107 {
108         struct mdd_object_user *mou;
109
110         ENTRY;
111
112         OBD_SLAB_ALLOC_PTR(mou, mdd_object_kmem);
113         if (mou == NULL)
114                 RETURN(ERR_PTR(-ENOMEM));
115
116         mou->mou_flags = flags;
117         mou->mou_uidgid = ((__u64)uid << 32) | gid;
118         mou->mou_opencount = 0;
119         mou->mou_deniednext = ktime_set(0, 0);
120
121         RETURN(mou);
122 }
123
124 /**
125  * Free a user and its sub-structures.
126  *
127  * \param mou [IN]  user to be freed.
128  */
129 static void mdd_obj_user_free(struct mdd_object_user *mou)
130 {
131         OBD_SLAB_FREE_PTR(mou, mdd_object_kmem);
132 }
133
134 /**
135  * Find if UID/GID already has this file open
136  *
137  * Caller should have write-locked \param mdd_obj.
138  * \param mdd_obj [IN] mdd_obj
139  * \param uid [IN] client uid
140  * \param gid [IN] client gid
141  * \retval user pointer or NULL if not found
142  */
143 static
144 struct mdd_object_user *mdd_obj_user_find(struct mdd_object *mdd_obj,
145                                           uid_t uid, gid_t gid, int flags)
146 {
147         struct mdd_object_user *mou;
148         __u64 uidgid;
149
150         ENTRY;
151
152         uidgid = ((__u64)uid << 32) | gid;
153         list_for_each_entry(mou, &mdd_obj->mod_users, mou_list) {
154                 if (mou->mou_uidgid == uidgid &&
155                     flags_helper(mou->mou_flags) == flags_helper(flags))
156                         RETURN(mou);
157         }
158         RETURN(NULL);
159 }
160
161 /**
162  * Add a user to the list of openers for this file
163  *
164  * Caller should have write-locked \param mdd_obj.
165  * \param mdd_obj [IN] mdd_obj
166  * \param mou [IN] user
167  * \retval 0 success
168  * \retval -ve failure
169  */
170 static int mdd_obj_user_add(struct mdd_object *mdd_obj,
171                             struct mdd_object_user *mou,
172                             bool denied)
173 {
174         struct mdd_device *mdd = mdd_obj2mdd_dev(mdd_obj);
175         struct mdd_object_user *tmp;
176         __u32 uid = mou->mou_uidgid >> 32;
177         __u32 gid = mou->mou_uidgid & ((1UL << 32) - 1);
178
179         ENTRY;
180
181         tmp = mdd_obj_user_find(mdd_obj, uid,
182                                 gid, mou->mou_flags);
183         if (tmp != NULL)
184                 RETURN(-EEXIST);
185
186         list_add_tail(&mou->mou_list, &mdd_obj->mod_users);
187
188         if (denied)
189                 /* next 'access denied' notification cannot happen before
190                  * mou_deniednext
191                  */
192                 mou->mou_deniednext =
193                         ktime_add(ktime_get(),
194                                   ktime_set(mdd->mdd_cl.mc_deniednext, 0));
195         else
196                 mou->mou_opencount++;
197
198         RETURN(0);
199 }
200 /**
201  * Remove UID from the list
202  *
203  * Caller should have write-locked \param mdd_obj.
204  * \param mdd_obj [IN] mdd_obj
205  * \param uid [IN] user
206  * \retval -ve failure
207  */
208 static int mdd_obj_user_remove(struct mdd_object *mdd_obj,
209                                struct mdd_object_user *mou)
210 {
211         ENTRY;
212
213         if (mou == NULL)
214                 RETURN(-ENOENT);
215
216         list_del_init(&mou->mou_list);
217
218         mdd_obj_user_free(mou);
219
220         RETURN(0);
221 }
222 int mdd_la_get(const struct lu_env *env, struct mdd_object *obj,
223                struct lu_attr *la)
224 {
225         int rc;
226
227         if (mdd_object_exists(obj) == 0)
228                 return -ENOENT;
229
230         rc = mdo_attr_get(env, obj, la);
231         if (unlikely(rc != 0)) {
232                 if (rc == -ENOENT)
233                         obj->mod_flags |= DEAD_OBJ;
234                 return rc;
235         }
236
237         if (la->la_valid & LA_FLAGS &&
238             la->la_flags & LUSTRE_ORPHAN_FL)
239                 obj->mod_flags |= ORPHAN_OBJ | DEAD_OBJ;
240
241         return 0;
242 }
243
244 struct mdd_thread_info *mdd_env_info(const struct lu_env *env)
245 {
246         struct mdd_thread_info *info;
247
248         lu_env_refill((struct lu_env *)env);
249         info = lu_context_key_get(&env->le_ctx, &mdd_thread_key);
250         LASSERT(info != NULL);
251         return info;
252 }
253
254 struct lu_buf *mdd_buf_get(const struct lu_env *env, void *area, ssize_t len)
255 {
256         struct lu_buf *buf;
257
258         buf = &mdd_env_info(env)->mti_buf[0];
259         buf->lb_buf = area;
260         buf->lb_len = len;
261         return buf;
262 }
263
264 const struct lu_buf *mdd_buf_get_const(const struct lu_env *env,
265                                        const void *area, ssize_t len)
266 {
267         struct lu_buf *buf;
268
269         buf = &mdd_env_info(env)->mti_buf[0];
270         buf->lb_buf = (void *)area;
271         buf->lb_len = len;
272         return buf;
273 }
274
275 struct lu_object *mdd_object_alloc(const struct lu_env *env,
276                                    const struct lu_object_header *hdr,
277                                    struct lu_device *d)
278 {
279         struct mdd_object *mdd_obj;
280         struct lu_object *o;
281
282         OBD_SLAB_ALLOC_PTR_GFP(mdd_obj, mdd_object_kmem, GFP_NOFS);
283         if (!mdd_obj)
284                 return NULL;
285
286         o = mdd2lu_obj(mdd_obj);
287         lu_object_init(o, NULL, d);
288         mdd_obj->mod_obj.mo_ops = &mdd_obj_ops;
289         mdd_obj->mod_obj.mo_dir_ops = &mdd_dir_ops;
290         mdd_obj->mod_count = 0;
291         o->lo_ops = &mdd_lu_obj_ops;
292         INIT_LIST_HEAD(&mdd_obj->mod_users);
293
294         return o;
295 }
296
297 static int mdd_object_init(const struct lu_env *env, struct lu_object *o,
298                            const struct lu_object_conf *unused)
299 {
300         struct mdd_device *d = lu2mdd_dev(o->lo_dev);
301         struct mdd_object *mdd_obj = lu2mdd_obj(o);
302         struct lu_object  *below;
303         struct lu_device  *under;
304         ENTRY;
305
306         mdd_obj->mod_cltime = ktime_set(0, 0);
307         under = &d->mdd_child->dd_lu_dev;
308         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
309         if (IS_ERR(below))
310                 RETURN(PTR_ERR(below));
311
312         lu_object_add(o, below);
313
314         RETURN(0);
315 }
316
317 static int mdd_object_start(const struct lu_env *env, struct lu_object *o)
318 {
319         int rc = 0;
320
321         if (lu_object_exists(o)) {
322                 struct mdd_object *mdd_obj = lu2mdd_obj(o);
323                 struct lu_attr *attr = MDD_ENV_VAR(env, la_for_start);
324
325                 rc = mdd_la_get(env, mdd_obj, attr);
326         }
327
328         return rc;
329 }
330
331 static void mdd_object_free(const struct lu_env *env, struct lu_object *o)
332 {
333         struct mdd_object *mdd = lu2mdd_obj(o);
334         struct mdd_object_user *mou, *tmp2;
335
336         /* free user list */
337         list_for_each_entry_safe(mou, tmp2, &mdd->mod_users, mou_list) {
338                 list_del(&mou->mou_list);
339                 mdd_obj_user_free(mou);
340         }
341
342         lu_object_fini(o);
343         OBD_SLAB_FREE_PTR(mdd, mdd_object_kmem);
344 }
345
346 static int mdd_object_print(const struct lu_env *env, void *cookie,
347                             lu_printer_t p, const struct lu_object *o)
348 {
349         struct mdd_object *mdd = lu2mdd_obj((struct lu_object *)o);
350
351         return (*p)(env, cookie,
352                     LUSTRE_MDD_NAME"-object@%p(open_count=%d, valid=%x, cltime=%lldns, flags=%lx)",
353                     mdd, mdd->mod_count, mdd->mod_valid,
354                     ktime_to_ns(mdd->mod_cltime), mdd->mod_flags);
355 }
356
357 static const struct lu_object_operations mdd_lu_obj_ops = {
358         .loo_object_init    = mdd_object_init,
359         .loo_object_start   = mdd_object_start,
360         .loo_object_free    = mdd_object_free,
361         .loo_object_print   = mdd_object_print,
362 };
363
364 struct mdd_object *mdd_object_find(const struct lu_env *env,
365                                    struct mdd_device *d,
366                                    const struct lu_fid *f)
367 {
368         return md2mdd_obj(md_object_find_slice(env, &d->mdd_md_dev, f));
369 }
370
371 /*
372  * No permission check is needed.
373  */
374 int mdd_attr_get(const struct lu_env *env, struct md_object *obj,
375                  struct md_attr *ma)
376 {
377         struct mdd_object *mdd_obj = md2mdd_obj(obj);
378         int               rc;
379
380         ENTRY;
381
382         rc = mdd_la_get(env, mdd_obj, &ma->ma_attr);
383         if ((ma->ma_need & MA_INODE) != 0 && mdd_is_dead_obj(mdd_obj))
384                 ma->ma_attr.la_nlink = 0;
385
386         RETURN(rc);
387 }
388
389 /*
390  * No permission check is needed.
391  */
392 static int mdd_xattr_get(const struct lu_env *env,
393                          struct md_object *obj, struct lu_buf *buf,
394                          const char *name)
395 {
396         struct mdd_object *mdd_obj = md2mdd_obj(obj);
397         struct mdd_device *mdd;
398         int rc;
399
400         ENTRY;
401
402         if (mdd_object_exists(mdd_obj) == 0) {
403                 CERROR("%s: object "DFID" not found: rc = -2\n",
404                        mdd_obj_dev_name(mdd_obj),
405                        PFID(mdd_object_fid(mdd_obj)));
406                 return -ENOENT;
407         }
408
409         /* If the object has been destroyed, then do not get LMVEA, because
410          * it needs to load stripes from the iteration of the master object,
411          * and it will cause problem if master object has been destroyed, see
412          * LU-6427 */
413         if (unlikely((mdd_obj->mod_flags & DEAD_OBJ) &&
414                      !(mdd_obj->mod_flags & ORPHAN_OBJ) &&
415                       strcmp(name, XATTR_NAME_LMV) == 0))
416                 RETURN(-ENOENT);
417
418         /* If the object has been delete from the namespace, then
419          * get linkEA should return -ENOENT as well */
420         if (unlikely((mdd_obj->mod_flags & (DEAD_OBJ | ORPHAN_OBJ)) &&
421                       strcmp(name, XATTR_NAME_LINK) == 0))
422                 RETURN(-ENOENT);
423
424         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
425         rc = mdo_xattr_get(env, mdd_obj, buf, name);
426         mdd_read_unlock(env, mdd_obj);
427
428         mdd = mdo2mdd(obj);
429
430         /* record only getting user xattrs and acls */
431         if (rc >= 0 &&
432             mdd_changelog_enabled(env, mdd, CL_GETXATTR) &&
433             (has_prefix(name, XATTR_USER_PREFIX) ||
434              has_prefix(name, XATTR_NAME_POSIX_ACL_ACCESS) ||
435              has_prefix(name, XATTR_NAME_POSIX_ACL_DEFAULT))) {
436                 struct thandle *handle;
437                 int rc2;
438
439                 LASSERT(mdo2fid(mdd_obj) != NULL);
440
441                 handle = mdd_trans_create(env, mdd);
442                 if (IS_ERR(handle))
443                         RETURN(PTR_ERR(handle));
444
445                 rc2 = mdd_declare_changelog_store(env, mdd, CL_GETXATTR, NULL,
446                                                   NULL, handle);
447                 if (rc2)
448                         GOTO(stop, rc2);
449
450                 rc2 = mdd_trans_start(env, mdd, handle);
451                 if (rc2)
452                         GOTO(stop, rc2);
453
454                 rc2 = mdd_changelog_data_store_by_fid(env, mdd, CL_GETXATTR, 0,
455                                                       mdo2fid(mdd_obj), name,
456                                                       handle);
457
458 stop:
459                 rc2 = mdd_trans_stop(env, mdd, rc2, handle);
460                 if (rc2)
461                         rc = rc2;
462         }
463
464         RETURN(rc);
465 }
466
467 /*
468  * Permission check is done when open,
469  * no need check again.
470  */
471 int mdd_readlink(const struct lu_env *env, struct md_object *obj,
472                  struct lu_buf *buf)
473 {
474         struct mdd_object *mdd_obj = md2mdd_obj(obj);
475         struct dt_object  *next;
476         loff_t             pos = 0;
477         int                rc;
478         ENTRY;
479
480         if (mdd_object_exists(mdd_obj) == 0) {
481                 CERROR("%s: object "DFID" not found: rc = -2\n",
482                        mdd_obj_dev_name(mdd_obj),PFID(mdd_object_fid(mdd_obj)));
483                 return -ENOENT;
484         }
485
486         next = mdd_object_child(mdd_obj);
487         LASSERT(next != NULL);
488         LASSERT(next->do_body_ops != NULL);
489         LASSERT(next->do_body_ops->dbo_read != NULL);
490         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
491         rc = dt_read(env, next, buf, &pos);
492         mdd_read_unlock(env, mdd_obj);
493         RETURN(rc);
494 }
495
496 /*
497  * No permission check is needed.
498  */
499 static int mdd_xattr_list(const struct lu_env *env, struct md_object *obj,
500                           struct lu_buf *buf)
501 {
502         struct mdd_object *mdd_obj = md2mdd_obj(obj);
503         int rc;
504
505         ENTRY;
506
507         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
508         rc = mdo_xattr_list(env, mdd_obj, buf);
509         mdd_read_unlock(env, mdd_obj);
510
511         /* If the buffer is NULL then we are only here to get the
512          * length of the xattr name list. */
513         if (rc < 0 || buf->lb_buf == NULL)
514                 RETURN(rc);
515
516         /*
517          * Filter out XATTR_NAME_LINK if this is an orphan object.  See
518          * mdd_xattr_get().
519          */
520         if (unlikely(mdd_obj->mod_flags & (DEAD_OBJ | ORPHAN_OBJ))) {
521                 char   *end = (char *)buf->lb_buf + rc;
522                 char   *p = buf->lb_buf;
523
524                 while (p < end) {
525                         char   *next = p + strlen(p) + 1;
526
527                         if (strcmp(p, XATTR_NAME_LINK) == 0) {
528                                 if (end - next > 0)
529                                         memmove(p, next, end - next);
530                                 rc -= next - p;
531                                 CDEBUG(D_INFO, "Filtered out "XATTR_NAME_LINK
532                                        " of orphan "DFID"\n",
533                                        PFID(mdd_object_fid(mdd_obj)));
534                                 break;
535                         }
536
537                         p = next;
538                 }
539         }
540
541         RETURN(rc);
542 }
543
544 int mdd_invalidate(const struct lu_env *env, struct md_object *obj)
545 {
546         return mdo_invalidate(env, md2mdd_obj(obj));
547 }
548
549 int mdd_declare_create_object_internal(const struct lu_env *env,
550                                        struct mdd_object *p,
551                                        struct mdd_object *c,
552                                        struct lu_attr *attr,
553                                        struct thandle *handle,
554                                        const struct md_op_spec *spec,
555                                        struct dt_allocation_hint *hint)
556 {
557         struct dt_object_format *dof = &mdd_env_info(env)->mti_dof;
558         const struct dt_index_features *feat = spec->sp_feat;
559         int rc;
560         ENTRY;
561
562         if (feat != &dt_directory_features && feat != NULL) {
563                 dof->dof_type = DFT_INDEX;
564                 dof->u.dof_idx.di_feat = feat;
565         } else {
566                 dof->dof_type = dt_mode_to_dft(attr->la_mode);
567                 if (dof->dof_type == DFT_REGULAR) {
568                         dof->u.dof_reg.striped =
569                                 md_should_create(spec->sp_cr_flags);
570                         if (spec->sp_cr_flags & MDS_OPEN_HAS_EA)
571                                 dof->u.dof_reg.striped = 0;
572                         /* is this replay? */
573                         if (spec->no_create)
574                                 dof->u.dof_reg.striped = 0;
575                 }
576         }
577
578         rc = mdo_declare_create_object(env, c, attr, hint, dof, handle);
579
580         RETURN(rc);
581 }
582
583 int mdd_create_object_internal(const struct lu_env *env, struct mdd_object *p,
584                                struct mdd_object *c, struct lu_attr *attr,
585                                struct thandle *handle,
586                                const struct md_op_spec *spec,
587                                struct dt_allocation_hint *hint)
588 {
589         struct dt_object_format *dof = &mdd_env_info(env)->mti_dof;
590         int rc;
591         ENTRY;
592
593         LASSERT(!mdd_object_exists(c));
594
595         rc = mdo_create_object(env, c, attr, hint, dof, handle);
596
597         RETURN(rc);
598 }
599
600 int mdd_attr_set_internal(const struct lu_env *env, struct mdd_object *obj,
601                           const struct lu_attr *attr, struct thandle *handle,
602                           int needacl)
603 {
604         int rc;
605         ENTRY;
606
607         rc = mdo_attr_set(env, obj, attr, handle);
608 #ifdef CONFIG_FS_POSIX_ACL
609         if (!rc && (attr->la_valid & LA_MODE) && needacl)
610                 rc = mdd_acl_chmod(env, obj, attr->la_mode, handle);
611 #endif
612         RETURN(rc);
613 }
614
615 int mdd_update_time(const struct lu_env *env, struct mdd_object *obj,
616                     const struct lu_attr *oattr, struct lu_attr *attr,
617                     struct thandle *handle)
618 {
619         int rc = 0;
620         ENTRY;
621
622         LASSERT(attr->la_valid & LA_CTIME);
623         LASSERT(oattr != NULL);
624
625         /* Make sure the ctime is increased only, however, it's not strictly
626          * reliable at here because there is not guarantee to hold lock on
627          * object, so we just bypass some unnecessary cmtime setting first
628          * and OSD has to check it again. */
629         if (attr->la_ctime < oattr->la_ctime)
630                 attr->la_valid &= ~(LA_MTIME | LA_CTIME);
631         else if (attr->la_valid == LA_CTIME &&
632                  attr->la_ctime == oattr->la_ctime)
633                 attr->la_valid &= ~LA_CTIME;
634
635         if (attr->la_valid != 0)
636                 rc = mdd_attr_set_internal(env, obj, attr, handle, 0);
637         RETURN(rc);
638 }
639
640 /*
641  * This gives the same functionality as the code between
642  * sys_chmod and inode_setattr
643  * chown_common and inode_setattr
644  * utimes and inode_setattr
645  * This API is ported from mds_fix_attr but remove some unnecesssary stuff.
646  */
647 static int mdd_fix_attr(const struct lu_env *env, struct mdd_object *obj,
648                         const struct lu_attr *oattr, struct lu_attr *la,
649                         const unsigned long flags)
650 {
651         struct lu_ucred  *uc;
652         int               rc = 0;
653         ENTRY;
654
655         if (!la->la_valid)
656                 RETURN(0);
657
658         /* Do not permit change file type */
659         if (la->la_valid & LA_TYPE)
660                 RETURN(-EPERM);
661
662         /* They should not be processed by setattr */
663         if (la->la_valid & (LA_NLINK | LA_RDEV | LA_BLKSIZE))
664                 RETURN(-EPERM);
665
666         LASSERT(oattr != NULL);
667
668         uc = lu_ucred_check(env);
669         if (uc == NULL)
670                 RETURN(0);
671
672         if (la->la_valid == LA_CTIME) {
673                 if (!(flags & MDS_PERM_BYPASS))
674                         /* This is only for set ctime when rename's source is
675                          * on remote MDS. */
676                         rc = mdd_may_delete(env, NULL, NULL, obj, oattr, NULL,
677                                             1, 0);
678                 if (rc == 0 && la->la_ctime <= oattr->la_ctime)
679                         la->la_valid &= ~LA_CTIME;
680                 RETURN(rc);
681         }
682
683         if (la->la_valid == LA_ATIME) {
684                 /* This is an atime-only attribute update for close RPCs. */
685                 if (la->la_atime < (oattr->la_atime +
686                                 mdd_obj2mdd_dev(obj)->mdd_atime_diff))
687                         la->la_valid &= ~LA_ATIME;
688                 RETURN(0);
689         }
690
691         /* Check if flags change. */
692         if (la->la_valid & LA_FLAGS) {
693                 unsigned int oldflags = oattr->la_flags &
694                                 (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL);
695                 unsigned int newflags = la->la_flags &
696                                 (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL);
697
698                 if ((uc->uc_fsuid != oattr->la_uid) &&
699                     !md_capable(uc, CFS_CAP_FOWNER))
700                         RETURN(-EPERM);
701
702                 /* The IMMUTABLE and APPEND_ONLY flags can
703                  * only be changed by the relevant capability. */
704                 if ((oldflags ^ newflags) &&
705                     !md_capable(uc, CFS_CAP_LINUX_IMMUTABLE))
706                         RETURN(-EPERM);
707
708                 if (!S_ISDIR(oattr->la_mode))
709                         la->la_flags &= ~(LUSTRE_DIRSYNC_FL | LUSTRE_TOPDIR_FL);
710         }
711
712         if (oattr->la_flags & (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL) &&
713             (la->la_valid & ~LA_FLAGS) &&
714             !(flags & MDS_PERM_BYPASS))
715                 RETURN(-EPERM);
716
717         /* Check for setting the obj time. */
718         if ((la->la_valid & (LA_MTIME | LA_ATIME | LA_CTIME)) &&
719             !(la->la_valid & ~(LA_MTIME | LA_ATIME | LA_CTIME))) {
720                 if ((uc->uc_fsuid != oattr->la_uid) &&
721                     !md_capable(uc, CFS_CAP_FOWNER)) {
722                         rc = mdd_permission_internal(env, obj, oattr,
723                                                      MAY_WRITE);
724                         if (rc)
725                                 RETURN(rc);
726                 }
727         }
728
729         if (la->la_valid & LA_KILL_SUID) {
730                 la->la_valid &= ~LA_KILL_SUID;
731                 if ((oattr->la_mode & S_ISUID) &&
732                     !(la->la_valid & LA_MODE)) {
733                         la->la_mode = oattr->la_mode;
734                         la->la_valid |= LA_MODE;
735                 }
736                 la->la_mode &= ~S_ISUID;
737         }
738
739         if (la->la_valid & LA_KILL_SGID) {
740                 la->la_valid &= ~LA_KILL_SGID;
741                 if (((oattr->la_mode & (S_ISGID | S_IXGRP)) ==
742                         (S_ISGID | S_IXGRP)) &&
743                     !(la->la_valid & LA_MODE)) {
744                         la->la_mode = oattr->la_mode;
745                         la->la_valid |= LA_MODE;
746                 }
747                 la->la_mode &= ~S_ISGID;
748         }
749
750         /* Make sure a caller can chmod. */
751         if (la->la_valid & LA_MODE) {
752                 if (!(flags & MDS_PERM_BYPASS) &&
753                     (uc->uc_fsuid != oattr->la_uid) &&
754                     !md_capable(uc, CFS_CAP_FOWNER))
755                         RETURN(-EPERM);
756
757                 if (la->la_mode == (umode_t) -1)
758                         la->la_mode = oattr->la_mode;
759                 else
760                         la->la_mode = (la->la_mode & S_IALLUGO) |
761                                         (oattr->la_mode & ~S_IALLUGO);
762
763                 /* Also check the setgid bit! */
764                 if (!lustre_in_group_p(uc, (la->la_valid & LA_GID) ?
765                                        la->la_gid : oattr->la_gid) &&
766                     !md_capable(uc, CFS_CAP_FSETID))
767                         la->la_mode &= ~S_ISGID;
768         } else {
769                la->la_mode = oattr->la_mode;
770         }
771
772         /* Make sure a caller can chown. */
773         if (la->la_valid & LA_UID) {
774                 if (la->la_uid == (uid_t) -1)
775                         la->la_uid = oattr->la_uid;
776                 if (((uc->uc_fsuid != oattr->la_uid) ||
777                      (la->la_uid != oattr->la_uid)) &&
778                     !md_capable(uc, CFS_CAP_CHOWN))
779                         RETURN(-EPERM);
780
781                 /* If the user or group of a non-directory has been
782                  * changed by a non-root user, remove the setuid bit.
783                  * 19981026 David C Niemi <niemi@tux.org>
784                  *
785                  * Changed this to apply to all users, including root,
786                  * to avoid some races. This is the behavior we had in
787                  * 2.0. The check for non-root was definitely wrong
788                  * for 2.2 anyway, as it should have been using
789                  * CAP_FSETID rather than fsuid -- 19990830 SD. */
790                 if (((oattr->la_mode & S_ISUID) == S_ISUID) &&
791                 !S_ISDIR(oattr->la_mode)) {
792                         la->la_mode &= ~S_ISUID;
793                         la->la_valid |= LA_MODE;
794                 }
795         }
796
797         /* Make sure caller can chgrp. */
798         if (la->la_valid & LA_GID) {
799                 if (la->la_gid == (gid_t) -1)
800                         la->la_gid = oattr->la_gid;
801                 if (((uc->uc_fsuid != oattr->la_uid) ||
802                      ((la->la_gid != oattr->la_gid) &&
803                       !lustre_in_group_p(uc, la->la_gid))) &&
804                     !md_capable(uc, CFS_CAP_CHOWN))
805                         RETURN(-EPERM);
806
807                 /* Likewise, if the user or group of a non-directory
808                  * has been changed by a non-root user, remove the
809                  * setgid bit UNLESS there is no group execute bit
810                  * (this would be a file marked for mandatory
811                  * locking).  19981026 David C Niemi <niemi@tux.org>
812                  *
813                  * Removed the fsuid check (see the comment above) --
814                  * 19990830 SD. */
815                 if (((oattr->la_mode & (S_ISGID | S_IXGRP)) ==
816                     (S_ISGID | S_IXGRP)) && !S_ISDIR(oattr->la_mode)) {
817                         la->la_mode &= ~S_ISGID;
818                         la->la_valid |= LA_MODE;
819                 }
820         }
821
822         if (la->la_valid & (LA_SIZE | LA_BLOCKS)) {
823                 if (!((flags & MDS_OWNEROVERRIDE) &&
824                       (uc->uc_fsuid == oattr->la_uid)) &&
825                     !(flags & MDS_PERM_BYPASS)) {
826                         rc = mdd_permission_internal(env, obj, oattr,
827                                                      MAY_WRITE);
828                         if (rc != 0)
829                                 RETURN(rc);
830                 }
831         }
832
833         if (la->la_valid & LA_CTIME) {
834                 /* The pure setattr, it has the priority over what is
835                  * already set, do not drop it if ctime is equal. */
836                 if (la->la_ctime < oattr->la_ctime)
837                         la->la_valid &= ~(LA_ATIME | LA_MTIME | LA_CTIME);
838         }
839
840         RETURN(0);
841 }
842
843 static int mdd_changelog_data_store_by_fid(const struct lu_env *env,
844                                            struct mdd_device *mdd,
845                                            enum changelog_rec_type type,
846                                            int flags, const struct lu_fid *fid,
847                                            const char *xattr_name,
848                                            struct thandle *handle)
849 {
850         const struct lu_ucred *uc = lu_ucred(env);
851         struct llog_changelog_rec *rec;
852         struct lu_buf *buf;
853         int reclen;
854         int xflags = CLFE_INVALID;
855         int rc;
856
857         flags = (flags & CLF_FLAGMASK) | CLF_VERSION | CLF_EXTRA_FLAGS;
858
859         if (uc) {
860                 if (uc->uc_jobid[0] != '\0')
861                         flags |= CLF_JOBID;
862                 xflags |= CLFE_UIDGID;
863                 xflags |= CLFE_NID;
864         }
865         if (type == CL_OPEN || type == CL_DN_OPEN)
866                 xflags |= CLFE_OPEN;
867         if (type == CL_SETXATTR || type == CL_GETXATTR)
868                 xflags |= CLFE_XATTR;
869
870         reclen = llog_data_len(LLOG_CHANGELOG_HDR_SZ +
871                                changelog_rec_offset(flags & CLF_SUPPORTED,
872                                                     xflags & CLFE_SUPPORTED));
873         buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf, reclen);
874         if (buf->lb_buf == NULL)
875                 RETURN(-ENOMEM);
876         rec = buf->lb_buf;
877
878         rec->cr_hdr.lrh_len = reclen;
879         rec->cr.cr_flags = flags;
880         rec->cr.cr_type = (__u32)type;
881         rec->cr.cr_tfid = *fid;
882         rec->cr.cr_namelen = 0;
883
884         if (flags & CLF_JOBID)
885                 mdd_changelog_rec_ext_jobid(&rec->cr, uc->uc_jobid);
886
887         if (flags & CLF_EXTRA_FLAGS) {
888                 mdd_changelog_rec_ext_extra_flags(&rec->cr, xflags);
889                 if (xflags & CLFE_UIDGID)
890                         mdd_changelog_rec_extra_uidgid(&rec->cr,
891                                                        uc->uc_uid, uc->uc_gid);
892                 if (xflags & CLFE_NID)
893                         mdd_changelog_rec_extra_nid(&rec->cr, uc->uc_nid);
894                 if (xflags & CLFE_OPEN)
895                         mdd_changelog_rec_extra_omode(&rec->cr, flags);
896                 if (xflags & CLFE_XATTR) {
897                         if (xattr_name == NULL)
898                                 RETURN(-EINVAL);
899                         mdd_changelog_rec_extra_xattr(&rec->cr, xattr_name);
900                 }
901         }
902
903         rc = mdd_changelog_store(env, mdd, rec, handle);
904         RETURN(rc);
905 }
906
907
908 /** Store a data change changelog record
909  * If this fails, we must fail the whole transaction; we don't
910  * want the change to commit without the log entry.
911  * \param mdd_obj - mdd_object of change
912  * \param handle - transaction handle
913  */
914 int mdd_changelog_data_store(const struct lu_env *env, struct mdd_device *mdd,
915                              enum changelog_rec_type type, int flags,
916                              struct mdd_object *mdd_obj, struct thandle *handle)
917 {
918         int                              rc;
919
920         LASSERT(mdd_obj != NULL);
921         LASSERT(handle != NULL);
922
923         if (!mdd_changelog_enabled(env, mdd, type))
924                 RETURN(0);
925
926         if (mdd_is_volatile_obj(mdd_obj))
927                 RETURN(0);
928
929         if ((type >= CL_MTIME) && (type <= CL_ATIME) &&
930             ktime_before(mdd->mdd_cl.mc_starttime, mdd_obj->mod_cltime)) {
931                 /* Don't need multiple updates in this log */
932                 /* Don't check under lock - no big deal if we get an extra
933                    entry */
934                 RETURN(0);
935         }
936
937         rc = mdd_changelog_data_store_by_fid(env, mdd, type, flags,
938                                              mdo2fid(mdd_obj), NULL, handle);
939         if (rc == 0)
940                 mdd_obj->mod_cltime = ktime_get();
941
942         RETURN(rc);
943 }
944
945 static int mdd_changelog_data_store_xattr(const struct lu_env *env,
946                                           struct mdd_device *mdd,
947                                           enum changelog_rec_type type,
948                                           int flags, struct mdd_object *mdd_obj,
949                                           const char *xattr_name,
950                                           struct thandle *handle)
951 {
952         int                              rc;
953
954         LASSERT(mdd_obj != NULL);
955         LASSERT(handle != NULL);
956
957         if (!mdd_changelog_enabled(env, mdd, type))
958                 RETURN(0);
959
960         if (mdd_is_volatile_obj(mdd_obj))
961                 RETURN(0);
962
963         if ((type >= CL_MTIME) && (type <= CL_ATIME) &&
964             ktime_before(mdd->mdd_cl.mc_starttime, mdd_obj->mod_cltime)) {
965                 /* Don't need multiple updates in this log */
966                 /* Don't check under lock - no big deal if we get an extra
967                  * entry
968                  */
969                 RETURN(0);
970         }
971
972         rc = mdd_changelog_data_store_by_fid(env, mdd, type, flags,
973                                              mdo2fid(mdd_obj), xattr_name,
974                                              handle);
975         if (rc == 0)
976                 mdd_obj->mod_cltime = ktime_get();
977
978         RETURN(rc);
979 }
980
981 static int mdd_changelog(const struct lu_env *env, enum changelog_rec_type type,
982                   int flags, struct md_device *m, const struct lu_fid *fid)
983 {
984         struct thandle *handle;
985         struct mdd_device *mdd = lu2mdd_dev(&m->md_lu_dev);
986         int rc;
987         ENTRY;
988
989         LASSERT(fid != NULL);
990
991         /* We'll check this again below, but we check now before we
992          * start a transaction. */
993         if (!mdd_changelog_enabled(env, mdd, type))
994                 RETURN(0);
995
996         handle = mdd_trans_create(env, mdd);
997         if (IS_ERR(handle))
998                 RETURN(PTR_ERR(handle));
999
1000         rc = mdd_declare_changelog_store(env, mdd, type, NULL, NULL, handle);
1001         if (rc)
1002                 GOTO(stop, rc);
1003
1004         rc = mdd_trans_start(env, mdd, handle);
1005         if (rc)
1006                 GOTO(stop, rc);
1007
1008         rc = mdd_changelog_data_store_by_fid(env, mdd, type, flags,
1009                                              fid, NULL, handle);
1010
1011 stop:
1012         rc = mdd_trans_stop(env, mdd, rc, handle);
1013
1014         RETURN(rc);
1015 }
1016
1017 /**
1018  * Save LMA extended attributes with data from \a ma.
1019  *
1020  * HSM and Size-On-MDS data will be extracted from \ma if they are valid, if
1021  * not, LMA EA will be first read from disk, modified and write back.
1022  *
1023  */
1024 /* Precedence for choosing record type when multiple
1025  * attributes change: setattr > mtime > ctime > atime
1026  * (ctime changes when mtime does, plus chmod/chown.
1027  * atime and ctime are independent.) */
1028 static int mdd_attr_set_changelog(const struct lu_env *env,
1029                                   struct md_object *obj, struct thandle *handle,
1030                                   __u64 valid)
1031 {
1032         struct mdd_device *mdd = mdo2mdd(obj);
1033         int bits, type = 0;
1034
1035         bits =  (valid & LA_SIZE)  ? 1 << CL_TRUNC : 0;
1036         bits |= (valid & ~(LA_CTIME|LA_MTIME|LA_ATIME)) ? 1 << CL_SETATTR : 0;
1037         bits |= (valid & LA_MTIME) ? 1 << CL_MTIME : 0;
1038         bits |= (valid & LA_CTIME) ? 1 << CL_CTIME : 0;
1039         bits |= (valid & LA_ATIME) ? 1 << CL_ATIME : 0;
1040         bits = bits & mdd->mdd_cl.mc_mask;
1041         /* This is an implementation limit rather than a protocol limit */
1042         CLASSERT(CL_LAST <= sizeof(int) * 8);
1043         if (bits == 0)
1044                 return 0;
1045
1046         /* The record type is the lowest non-masked set bit */
1047         type = __ffs(bits);
1048
1049         /* FYI we only store the first CLF_FLAGMASK bits of la_valid */
1050         return mdd_changelog_data_store(env, mdd, type, (int)valid,
1051                                         md2mdd_obj(obj), handle);
1052 }
1053
1054 static int mdd_declare_attr_set(const struct lu_env *env,
1055                                 struct mdd_device *mdd,
1056                                 struct mdd_object *obj,
1057                                 const struct lu_attr *attr,
1058                                 struct thandle *handle)
1059 {
1060         int rc;
1061
1062         rc = mdo_declare_attr_set(env, obj, attr, handle);
1063         if (rc)
1064                 return rc;
1065
1066 #ifdef CONFIG_FS_POSIX_ACL
1067         if (attr->la_valid & LA_MODE) {
1068                 mdd_read_lock(env, obj, MOR_TGT_CHILD);
1069                 rc = mdo_xattr_get(env, obj, &LU_BUF_NULL,
1070                                    XATTR_NAME_ACL_ACCESS);
1071                 mdd_read_unlock(env, obj);
1072                 if (rc == -EOPNOTSUPP || rc == -ENODATA)
1073                         rc = 0;
1074                 else if (rc < 0)
1075                         return rc;
1076
1077                 if (rc != 0) {
1078                         struct lu_buf *buf = mdd_buf_get(env, NULL, rc);
1079                         rc = mdo_declare_xattr_set(env, obj, buf,
1080                                                    XATTR_NAME_ACL_ACCESS, 0,
1081                                                    handle);
1082                         if (rc)
1083                                 return rc;
1084                 }
1085         }
1086 #endif
1087
1088         rc = mdd_declare_changelog_store(env, mdd, CL_SETXATTR, NULL, NULL,
1089                                          handle);
1090         return rc;
1091 }
1092
1093 /*
1094  * LU-3671
1095  *
1096  * permission changes may require sync operation, to mitigate performance
1097  * impact, only do this for dir and when permission is reduced.
1098  *
1099  * For regular files, version is updated with permission change (see VBR), async
1100  * permission won't cause any issue, while missing permission change on
1101  * directory may affect accessibility of other objects after recovery.
1102  */
1103 static inline bool permission_needs_sync(const struct lu_attr *old,
1104                                          const struct lu_attr *new)
1105 {
1106         if (!S_ISDIR(old->la_mode))
1107                 return false;
1108
1109         if (new->la_valid & (LA_UID | LA_GID))
1110                 return true;
1111
1112         if (new->la_valid & LA_MODE &&
1113             new->la_mode & (S_ISUID | S_ISGID | S_ISVTX))
1114                 return true;
1115
1116         if ((new->la_valid & LA_MODE) &&
1117             ((new->la_mode & old->la_mode) & S_IRWXUGO) !=
1118              (old->la_mode & S_IRWXUGO))
1119                 return true;
1120
1121         return false;
1122 }
1123
1124 static inline __u64 mdd_lmm_dom_size(void *buf)
1125 {
1126         struct lov_mds_md *lmm = buf;
1127         struct lov_comp_md_v1 *comp_v1;
1128         struct lov_mds_md *v1;
1129         __u32 off;
1130
1131         if (lmm == NULL)
1132                 return 0;
1133
1134         if (le32_to_cpu(lmm->lmm_magic) != LOV_MAGIC_COMP_V1)
1135                 return 0;
1136
1137         comp_v1 = (struct lov_comp_md_v1 *)lmm;
1138         off = le32_to_cpu(comp_v1->lcm_entries[0].lcme_offset);
1139         v1 = (struct lov_mds_md *)((char *)comp_v1 + off);
1140
1141         /* DoM entry is the first entry always */
1142         if (lov_pattern(le32_to_cpu(v1->lmm_pattern)) == LOV_PATTERN_MDT)
1143                 return le64_to_cpu(comp_v1->lcm_entries[0].lcme_extent.e_end);
1144
1145         return 0;
1146 }
1147
1148 /* set attr and LOV EA at once, return updated attr */
1149 int mdd_attr_set(const struct lu_env *env, struct md_object *obj,
1150                  const struct md_attr *ma)
1151 {
1152         struct mdd_object *mdd_obj = md2mdd_obj(obj);
1153         struct mdd_device *mdd = mdo2mdd(obj);
1154         struct thandle *handle = NULL;
1155         struct lu_attr *la_copy = &mdd_env_info(env)->mti_la_for_fix;
1156         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
1157         const struct lu_attr *la = &ma->ma_attr;
1158         struct lu_ucred  *uc;
1159         int rc;
1160         ENTRY;
1161
1162         /* we do not use ->attr_set() for LOV/HSM EA any more */
1163         LASSERT((ma->ma_valid & MA_LOV) == 0);
1164         LASSERT((ma->ma_valid & MA_HSM) == 0);
1165
1166         rc = mdd_la_get(env, mdd_obj, attr);
1167         if (rc)
1168                 RETURN(rc);
1169
1170         *la_copy = ma->ma_attr;
1171         rc = mdd_fix_attr(env, mdd_obj, attr, la_copy, ma->ma_attr_flags);
1172         if (rc)
1173                 RETURN(rc);
1174
1175         /* no need to setattr anymore */
1176         if (la_copy->la_valid == 0) {
1177                 CDEBUG(D_INODE, "%s: no valid attribute on "DFID", previous"
1178                        "valid is %#llx\n", mdd2obd_dev(mdd)->obd_name,
1179                        PFID(mdo2fid(mdd_obj)), la->la_valid);
1180
1181                 RETURN(0);
1182         }
1183
1184         /* If an unprivileged user changes group of some file,
1185          * the setattr operation will be processed synchronously to
1186          * honor the quota limit of the corresponding group. see LU-5152 */
1187         uc = lu_ucred_check(env);
1188         if (S_ISREG(attr->la_mode) && la->la_valid & LA_GID &&
1189             la->la_gid != attr->la_gid && uc != NULL && uc->uc_fsuid != 0) {
1190                 la_copy->la_valid |= LA_FLAGS;
1191                 la_copy->la_flags |= LUSTRE_SET_SYNC_FL;
1192
1193                 /* Flush the possible existing sync requests to OSTs to
1194                  * keep the order of sync for the current setattr operation
1195                  * will be sent directly to OSTs. see LU-5152 */
1196                 rc = dt_sync(env, mdd->mdd_child);
1197                 if (rc)
1198                         GOTO(out, rc);
1199         }
1200
1201         handle = mdd_trans_create(env, mdd);
1202         if (IS_ERR(handle)) {
1203                 rc = PTR_ERR(handle);
1204                 handle = NULL;
1205
1206                 GOTO(out, rc);
1207         }
1208
1209         rc = mdd_declare_attr_set(env, mdd, mdd_obj, la_copy, handle);
1210         if (rc)
1211                 GOTO(out, rc);
1212
1213         rc = mdd_trans_start(env, mdd, handle);
1214         if (rc)
1215                 GOTO(out, rc);
1216
1217         if (mdd->mdd_sync_permission && permission_needs_sync(attr, la))
1218                 handle->th_sync = 1;
1219
1220         if (la->la_valid & (LA_MTIME | LA_CTIME))
1221                 CDEBUG(D_INODE, "setting mtime %llu, ctime %llu\n",
1222                        la->la_mtime, la->la_ctime);
1223
1224         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
1225
1226         /* LU-10509: setattr of LA_SIZE should be skipped case of DOM,
1227          * otherwise following truncate will do nothing and truncated
1228          * data may be read again. This is a quick fix until LU-11033
1229          * will be resolved.
1230          */
1231         if (la_copy->la_valid & LA_SIZE) {
1232                 struct lu_buf *lov_buf = mdd_buf_get(env, NULL, 0);
1233
1234                 rc = mdd_get_lov_ea(env, mdd_obj, lov_buf);
1235                 if (rc) {
1236                         rc = 0;
1237                 } else {
1238                         if (mdd_lmm_dom_size(lov_buf->lb_buf) > 0)
1239                                 la_copy->la_valid &= ~LA_SIZE;
1240                         lu_buf_free(lov_buf);
1241                 }
1242         }
1243
1244         if (la_copy->la_valid) {
1245                 rc = mdd_attr_set_internal(env, mdd_obj, la_copy, handle, 1);
1246
1247                 if (rc == -EDQUOT && la_copy->la_flags & LUSTRE_SET_SYNC_FL) {
1248                         /* rollback to the original gid */
1249                         la_copy->la_flags &= ~LUSTRE_SET_SYNC_FL;
1250                         la_copy->la_gid = attr->la_gid;
1251                         mdd_attr_set_internal(env, mdd_obj, la_copy, handle, 1);
1252                 }
1253         }
1254         mdd_write_unlock(env, mdd_obj);
1255
1256 out:
1257         if (rc == 0)
1258                 rc = mdd_attr_set_changelog(env, obj, handle,
1259                                             la_copy->la_valid);
1260
1261         if (handle != NULL)
1262                 rc = mdd_trans_stop(env, mdd, rc, handle);
1263
1264         return rc;
1265 }
1266
1267 static int mdd_xattr_sanity_check(const struct lu_env *env,
1268                                   struct mdd_object *obj,
1269                                   const struct lu_attr *attr,
1270                                   const char *name)
1271 {
1272         struct lu_ucred *uc     = lu_ucred_assert(env);
1273         ENTRY;
1274
1275         if (attr->la_flags & (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL))
1276                 RETURN(-EPERM);
1277
1278         if (strncmp(XATTR_USER_PREFIX, name,
1279                     sizeof(XATTR_USER_PREFIX) - 1) == 0) {
1280                 /* For sticky directories, only the owner and privileged user
1281                  * can write attributes. */
1282                 if (S_ISDIR(attr->la_mode) && (attr->la_mode & S_ISVTX) &&
1283                     (uc->uc_fsuid != attr->la_uid) &&
1284                     !md_capable(uc, CFS_CAP_FOWNER))
1285                         RETURN(-EPERM);
1286         } else if (strcmp(name, XATTR_NAME_SOM) != 0 &&
1287                    (uc->uc_fsuid != attr->la_uid) &&
1288                    !md_capable(uc, CFS_CAP_FOWNER)) {
1289                 RETURN(-EPERM);
1290         }
1291
1292         RETURN(0);
1293 }
1294
1295 /**
1296  * Check if a string begins with a given prefix.
1297  *
1298  * \param str     String to check
1299  * \param prefix  Substring to check at the beginning of \a str
1300  * \return true/false whether the condition is verified.
1301  */
1302 static inline bool has_prefix(const char *str, const char *prefix)
1303 {
1304         return strncmp(prefix, str, strlen(prefix)) == 0;
1305 }
1306
1307 /**
1308  * Indicate the kind of changelog to store (if any) for a xattr set/del.
1309  *
1310  * \param[in]  xattr_name  Full extended attribute name.
1311  *
1312  * \return The type of changelog to use, or -1 if no changelog is to be emitted.
1313  */
1314 static enum changelog_rec_type
1315 mdd_xattr_changelog_type(const struct lu_env *env, struct mdd_device *mdd,
1316                          const char *xattr_name)
1317 {
1318         /* Layout changes systematically recorded */
1319         if (strcmp(XATTR_NAME_LOV, xattr_name) == 0 ||
1320             strncmp(XATTR_LUSTRE_LOV, xattr_name,
1321                     strlen(XATTR_LUSTRE_LOV)) == 0)
1322                 return CL_LAYOUT;
1323
1324         /* HSM information changes systematically recorded */
1325         if (strcmp(XATTR_NAME_HSM, xattr_name) == 0)
1326                 return CL_HSM;
1327
1328         if (has_prefix(xattr_name, XATTR_USER_PREFIX) ||
1329             has_prefix(xattr_name, XATTR_NAME_POSIX_ACL_ACCESS) ||
1330             has_prefix(xattr_name, XATTR_NAME_POSIX_ACL_DEFAULT) ||
1331             has_prefix(xattr_name, XATTR_TRUSTED_PREFIX) ||
1332             has_prefix(xattr_name, XATTR_SECURITY_PREFIX))
1333                 return CL_SETXATTR;
1334
1335         return -1;
1336 }
1337
1338 static int mdd_declare_xattr_set(const struct lu_env *env,
1339                                  struct mdd_device *mdd,
1340                                  struct mdd_object *obj,
1341                                  const struct lu_buf *buf,
1342                                  const char *name,
1343                                  int fl, struct thandle *handle)
1344 {
1345         enum changelog_rec_type type;
1346         int rc;
1347
1348         rc = mdo_declare_xattr_set(env, obj, buf, name, fl, handle);
1349         if (rc)
1350                 return rc;
1351
1352         type = mdd_xattr_changelog_type(env, mdd, name);
1353         if (type < 0)
1354                 return 0; /* no changelog to store */
1355
1356         return mdd_declare_changelog_store(env, mdd, type, NULL, NULL, handle);
1357 }
1358
1359 /*
1360  * Compare current and future data of HSM EA and add a changelog if needed.
1361  *
1362  * Caller should have write-locked \param obj.
1363  *
1364  * \param buf - Future HSM EA content.
1365  * \retval 0 if no changelog is needed or changelog was added properly.
1366  * \retval -ve errno if there was a problem
1367  */
1368 static int mdd_hsm_update_locked(const struct lu_env *env,
1369                                  struct md_object *obj,
1370                                  const struct lu_buf *buf,
1371                                  struct thandle *handle, int *cl_flags)
1372 {
1373         struct mdd_thread_info *info = mdd_env_info(env);
1374         struct mdd_object      *mdd_obj = md2mdd_obj(obj);
1375         struct lu_buf          *current_buf;
1376         struct md_hsm          *current_mh;
1377         struct md_hsm          *new_mh;
1378         int                     rc;
1379         ENTRY;
1380
1381         OBD_ALLOC_PTR(current_mh);
1382         if (current_mh == NULL)
1383                 RETURN(-ENOMEM);
1384
1385         /* Read HSM attrs from disk */
1386         current_buf = lu_buf_check_and_alloc(&info->mti_xattr_buf,
1387                                 mdo2mdd(obj)->mdd_dt_conf.ddp_max_ea_size);
1388         rc = mdo_xattr_get(env, mdd_obj, current_buf, XATTR_NAME_HSM);
1389         rc = lustre_buf2hsm(current_buf->lb_buf, rc, current_mh);
1390         if (rc < 0 && rc != -ENODATA)
1391                 GOTO(free, rc);
1392         else if (rc == -ENODATA)
1393                 current_mh->mh_flags = 0;
1394
1395         /* Map future HSM xattr */
1396         OBD_ALLOC_PTR(new_mh);
1397         if (new_mh == NULL)
1398                 GOTO(free, rc = -ENOMEM);
1399         lustre_buf2hsm(buf->lb_buf, buf->lb_len, new_mh);
1400
1401         rc = 0;
1402
1403         /* Flags differ, set flags for the changelog that will be added */
1404         if (current_mh->mh_flags != new_mh->mh_flags) {
1405                 hsm_set_cl_event(cl_flags, HE_STATE);
1406                 if (new_mh->mh_flags & HS_DIRTY)
1407                         hsm_set_cl_flags(cl_flags, CLF_HSM_DIRTY);
1408         }
1409
1410         OBD_FREE_PTR(new_mh);
1411         EXIT;
1412 free:
1413         OBD_FREE_PTR(current_mh);
1414         return rc;
1415 }
1416
1417 static int mdd_object_pfid_replace(const struct lu_env *env,
1418                                    struct mdd_object *o)
1419 {
1420         struct mdd_device *mdd = mdo2mdd(&o->mod_obj);
1421         struct thandle *handle;
1422         int rc;
1423
1424         handle = mdd_trans_create(env, mdd);
1425         if (IS_ERR(handle))
1426                 RETURN(PTR_ERR(handle));
1427
1428         handle->th_complex = 1;
1429
1430         /* it doesn't need to track the PFID update via llog, because LFSCK
1431          * will repair it even it goes wrong */
1432         rc = mdd_declare_xattr_set(env, mdd, o, NULL, XATTR_NAME_FID,
1433                                    0, handle);
1434         if (rc)
1435                 GOTO(out, rc);
1436
1437         rc = mdd_trans_start(env, mdd, handle);
1438         if (rc != 0)
1439                 GOTO(out, rc);
1440
1441         rc = mdo_xattr_set(env, o, NULL, XATTR_NAME_FID, 0, handle);
1442         if (rc)
1443                 GOTO(out, rc);
1444
1445 out:
1446         mdd_trans_stop(env, mdd, rc, handle);
1447         return rc;
1448 }
1449
1450
1451 static int mdd_declare_xattr_del(const struct lu_env *env,
1452                                  struct mdd_device *mdd,
1453                                  struct mdd_object *obj,
1454                                  const char *name,
1455                                  struct thandle *handle);
1456
1457 static int mdd_xattr_del(const struct lu_env *env, struct md_object *obj,
1458                          const char *name);
1459
1460 static int mdd_xattr_merge(const struct lu_env *env, struct md_object *md_obj,
1461                            struct md_object *md_vic)
1462 {
1463         struct mdd_device *mdd = mdo2mdd(md_obj);
1464         struct mdd_object *obj = md2mdd_obj(md_obj);
1465         struct mdd_object *vic = md2mdd_obj(md_vic);
1466         struct lu_buf *buf = &mdd_env_info(env)->mti_buf[0];
1467         struct lu_buf *buf_vic = &mdd_env_info(env)->mti_buf[1];
1468         struct lov_mds_md *lmm;
1469         struct thandle *handle;
1470         int rc;
1471         ENTRY;
1472
1473         rc = lu_fid_cmp(mdo2fid(obj), mdo2fid(vic));
1474         if (rc == 0) /* same fid */
1475                 RETURN(-EPERM);
1476
1477         handle = mdd_trans_create(env, mdd);
1478         if (IS_ERR(handle))
1479                 RETURN(PTR_ERR(handle));
1480
1481         if (rc > 0) {
1482                 mdd_write_lock(env, obj, MOR_TGT_CHILD);
1483                 mdd_write_lock(env, vic, MOR_TGT_CHILD);
1484         } else {
1485                 mdd_write_lock(env, vic, MOR_TGT_CHILD);
1486                 mdd_write_lock(env, obj, MOR_TGT_CHILD);
1487         }
1488
1489         /* get EA of victim file */
1490         memset(buf_vic, 0, sizeof(*buf_vic));
1491         rc = mdd_get_lov_ea(env, vic, buf_vic);
1492         if (rc < 0) {
1493                 if (rc == -ENODATA)
1494                         rc = 0;
1495                 GOTO(out, rc);
1496         }
1497
1498         /* parse the layout of victim file */
1499         lmm = buf_vic->lb_buf;
1500         if (le32_to_cpu(lmm->lmm_magic) != LOV_MAGIC_COMP_V1)
1501                 GOTO(out, rc = -EINVAL);
1502
1503         /* save EA of target file for restore */
1504         memset(buf, 0, sizeof(*buf));
1505         rc = mdd_get_lov_ea(env, obj, buf);
1506         if (rc < 0)
1507                 GOTO(out, rc);
1508
1509         /* Get rid of the layout from victim object */
1510         rc = mdd_declare_xattr_del(env, mdd, vic, XATTR_NAME_LOV, handle);
1511         if (rc)
1512                 GOTO(out, rc);
1513
1514         rc = mdd_declare_xattr_set(env, mdd, obj, buf_vic, XATTR_LUSTRE_LOV,
1515                                    LU_XATTR_MERGE, handle);
1516         if (rc)
1517                 GOTO(out, rc);
1518
1519         rc = mdd_trans_start(env, mdd, handle);
1520         if (rc != 0)
1521                 GOTO(out, rc);
1522
1523         rc = mdo_xattr_set(env, obj, buf_vic, XATTR_LUSTRE_LOV, LU_XATTR_MERGE,
1524                            handle);
1525         if (rc)
1526                 GOTO(out, rc);
1527
1528         rc = mdo_xattr_del(env, vic, XATTR_NAME_LOV, handle);
1529         if (rc) /* wtf? */
1530                 GOTO(out_restore, rc);
1531
1532         (void)mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, obj, handle);
1533         (void)mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, vic, handle);
1534         EXIT;
1535
1536 out_restore:
1537         if (rc) {
1538                 int rc2 = mdo_xattr_set(env, obj, buf, XATTR_NAME_LOV,
1539                                         LU_XATTR_REPLACE, handle);
1540                 if (rc2)
1541                         CERROR("%s: failed to rollback of layout of: "DFID
1542                                ": %d, file state unknown\n",
1543                                mdd_obj_dev_name(obj), PFID(mdo2fid(obj)), rc2);
1544         }
1545
1546 out:
1547         mdd_trans_stop(env, mdd, rc, handle);
1548         mdd_write_unlock(env, obj);
1549         mdd_write_unlock(env, vic);
1550         lu_buf_free(buf);
1551         lu_buf_free(buf_vic);
1552
1553         if (!rc)
1554                 (void) mdd_object_pfid_replace(env, obj);
1555
1556         return rc;
1557 }
1558
1559 /**
1560  * Extract the mirror with specified mirror id, and store the splitted
1561  * mirror layout to @buf.
1562  *
1563  * \param[in] comp_v1   mirrored layout
1564  * \param[in] mirror_id the mirror with mirror_id to be extracted
1565  * \param[out] buf      store the layout excluding the extracted mirror,
1566  *                      caller free the buffer we allocated in this function
1567  * \param[out] buf_vic  store the extracted layout, caller free the buffer
1568  *                      we allocated in this function
1569  *
1570  * \retval      0 on success; < 0 if error happens
1571  */
1572 static int mdd_split_ea(struct lov_comp_md_v1 *comp_v1, __u16 mirror_id,
1573                         struct lu_buf *buf, struct lu_buf *buf_vic)
1574 {
1575         struct lov_comp_md_v1 *comp_rem;
1576         struct lov_comp_md_v1 *comp_vic;
1577         struct lov_comp_md_entry_v1 *entry;
1578         struct lov_comp_md_entry_v1 *entry_rem;
1579         struct lov_comp_md_entry_v1 *entry_vic;
1580         __u16 mirror_cnt;
1581         __u16 comp_cnt, count = 0;
1582         int lmm_size, lmm_size_vic = 0;
1583         int i, j, k;
1584         int offset, offset_rem, offset_vic;
1585
1586         mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
1587         /* comp_v1 should contains more than 1 mirror */
1588         if (mirror_cnt <= 1)
1589                 return -EINVAL;
1590         comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
1591         lmm_size = le32_to_cpu(comp_v1->lcm_size);
1592
1593         for (i = 0; i < comp_cnt; i++) {
1594                 entry = &comp_v1->lcm_entries[i];
1595                 if (mirror_id_of(le32_to_cpu(entry->lcme_id)) == mirror_id) {
1596                         count++;
1597                         lmm_size_vic += sizeof(*entry);
1598                         lmm_size_vic += le32_to_cpu(entry->lcme_size);
1599                 } else if (count > 0) {
1600                         /* find the specified mirror */
1601                         break;
1602                 }
1603         }
1604
1605         if (count == 0)
1606                 return -EINVAL;
1607
1608         lu_buf_alloc(buf, lmm_size - lmm_size_vic);
1609         if (!buf->lb_buf)
1610                 return -ENOMEM;
1611
1612         lu_buf_alloc(buf_vic, sizeof(*comp_vic) + lmm_size_vic);
1613         if (!buf_vic->lb_buf) {
1614                 lu_buf_free(buf);
1615                 return -ENOMEM;
1616         }
1617
1618         comp_rem = (struct lov_comp_md_v1 *)buf->lb_buf;
1619         comp_vic = (struct lov_comp_md_v1 *)buf_vic->lb_buf;
1620
1621         memcpy(comp_rem, comp_v1, sizeof(*comp_v1));
1622         comp_rem->lcm_mirror_count = cpu_to_le16(mirror_cnt - 2);
1623         comp_rem->lcm_entry_count = cpu_to_le32(comp_cnt - count);
1624         comp_rem->lcm_size = cpu_to_le32(lmm_size - lmm_size_vic);
1625         if (!comp_rem->lcm_mirror_count)
1626                 comp_rem->lcm_flags = cpu_to_le16(LCM_FL_NONE);
1627
1628         memset(comp_vic, 0, sizeof(*comp_v1));
1629         comp_vic->lcm_magic = cpu_to_le32(LOV_MAGIC_COMP_V1);
1630         comp_vic->lcm_mirror_count = 0;
1631         comp_vic->lcm_entry_count = cpu_to_le32(count);
1632         comp_vic->lcm_size = cpu_to_le32(lmm_size_vic + sizeof(*comp_vic));
1633         comp_vic->lcm_flags = cpu_to_le16(LCM_FL_NONE);
1634         comp_vic->lcm_layout_gen = 0;
1635
1636         offset = sizeof(*comp_v1) + sizeof(*entry) * comp_cnt;
1637         offset_rem = sizeof(*comp_rem) +
1638                      sizeof(*entry_rem) * (comp_cnt - count);
1639         offset_vic = sizeof(*comp_vic) + sizeof(*entry_vic) * count;
1640         for (i = j = k = 0; i < comp_cnt; i++) {
1641                 struct lov_mds_md *lmm, *lmm_dst;
1642                 bool vic = false;
1643
1644                 entry = &comp_v1->lcm_entries[i];
1645                 entry_vic = &comp_vic->lcm_entries[j];
1646                 entry_rem = &comp_rem->lcm_entries[k];
1647
1648                 if (mirror_id_of(le32_to_cpu(entry->lcme_id)) == mirror_id)
1649                         vic = true;
1650
1651                 /* copy component entry */
1652                 if (vic) {
1653                         memcpy(entry_vic, entry, sizeof(*entry));
1654                         entry_vic->lcme_flags &= cpu_to_le32(LCME_FL_INIT);
1655                         entry_vic->lcme_offset = cpu_to_le32(offset_vic);
1656                         j++;
1657                 } else {
1658                         memcpy(entry_rem, entry, sizeof(*entry));
1659                         entry_rem->lcme_offset = cpu_to_le32(offset_rem);
1660                         k++;
1661                 }
1662
1663                 lmm = (struct lov_mds_md *)((char *)comp_v1 + offset);
1664                 if (vic)
1665                         lmm_dst = (struct lov_mds_md *)
1666                                         ((char *)comp_vic + offset_vic);
1667                 else
1668                         lmm_dst = (struct lov_mds_md *)
1669                                         ((char *)comp_rem + offset_rem);
1670
1671                 /* copy component entry blob */
1672                 memcpy(lmm_dst, lmm, le32_to_cpu(entry->lcme_size));
1673
1674                 /* blob offset advance */
1675                 offset += le32_to_cpu(entry->lcme_size);
1676                 if (vic)
1677                         offset_vic += le32_to_cpu(entry->lcme_size);
1678                 else
1679                         offset_rem += le32_to_cpu(entry->lcme_size);
1680         }
1681
1682         return 0;
1683 }
1684
1685 static int mdd_xattr_split(const struct lu_env *env, struct md_object *md_obj,
1686                            struct md_rejig_data *mrd)
1687 {
1688         struct mdd_device *mdd = mdo2mdd(md_obj);
1689         struct mdd_object *obj = md2mdd_obj(md_obj);
1690         struct mdd_object *vic = md2mdd_obj(mrd->mrd_obj);
1691         struct lu_buf *buf = &mdd_env_info(env)->mti_buf[0];
1692         struct lu_buf *buf_save = &mdd_env_info(env)->mti_buf[1];
1693         struct lu_buf *buf_vic = &mdd_env_info(env)->mti_buf[2];
1694         struct lov_comp_md_v1 *lcm;
1695         struct thandle *handle;
1696         int rc;
1697         ENTRY;
1698
1699         rc = lu_fid_cmp(mdo2fid(obj), mdo2fid(vic));
1700         if (rc == 0) /* same fid */
1701                 RETURN(-EPERM);
1702
1703         handle = mdd_trans_create(env, mdd);
1704         if (IS_ERR(handle))
1705                 RETURN(PTR_ERR(handle));
1706
1707         if (rc > 0) {
1708                 mdd_write_lock(env, obj, MOR_TGT_CHILD);
1709                 mdd_write_lock(env, vic, MOR_TGT_CHILD);
1710         } else {
1711                 mdd_write_lock(env, vic, MOR_TGT_CHILD);
1712                 mdd_write_lock(env, obj, MOR_TGT_CHILD);
1713         }
1714
1715         /* get EA of mirrored file */
1716         memset(buf_save, 0, sizeof(*buf));
1717         rc = mdd_get_lov_ea(env, obj, buf_save);
1718         if (rc < 0)
1719                 GOTO(out, rc);
1720
1721         lcm = buf_save->lb_buf;
1722         if (le32_to_cpu(lcm->lcm_magic) != LOV_MAGIC_COMP_V1)
1723                 GOTO(out, rc = -EINVAL);
1724
1725         /**
1726          * Extract the mirror with specified mirror id, and store the splitted
1727          * mirror layout to the victim file.
1728          */
1729         memset(buf, 0, sizeof(*buf));
1730         memset(buf_vic, 0, sizeof(*buf_vic));
1731         rc = mdd_split_ea(lcm, mrd->mrd_mirror_id, buf, buf_vic);
1732         if (rc < 0)
1733                 GOTO(out, rc);
1734
1735         rc = mdd_declare_xattr_set(env, mdd, obj, buf, XATTR_NAME_LOV,
1736                                    LU_XATTR_SPLIT, handle);
1737         if (rc)
1738                 GOTO(out, rc);
1739         rc = mdd_declare_xattr_set(env, mdd, vic, buf_vic, XATTR_NAME_LOV,
1740                                    LU_XATTR_SPLIT, handle);
1741         if (rc)
1742                 GOTO(out, rc);
1743
1744         rc = mdd_trans_start(env, mdd, handle);
1745         if (rc)
1746                 GOTO(out, rc);
1747
1748         rc = mdo_xattr_set(env, obj, buf, XATTR_NAME_LOV, LU_XATTR_REPLACE,
1749                            handle);
1750         if (rc)
1751                 GOTO(out, rc);
1752
1753         rc = mdo_xattr_set(env, vic, buf_vic, XATTR_NAME_LOV, LU_XATTR_CREATE,
1754                            handle);
1755         if (rc)
1756                 GOTO(out_restore, rc);
1757
1758         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, obj, handle);
1759         if (rc)
1760                 GOTO(out, rc);
1761
1762         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, vic, handle);
1763         if (rc)
1764                 GOTO(out, rc);
1765         EXIT;
1766
1767 out_restore:
1768         if (rc) {
1769                 /* restore obj's layout */
1770                 int rc2 = mdo_xattr_set(env, obj, buf_save, XATTR_NAME_LOV,
1771                                         LU_XATTR_REPLACE, handle);
1772                 if (rc2)
1773                         CERROR("%s: failed to rollback of layout of: "DFID
1774                                ": %d, file state unkonwn.\n",
1775                                mdd_obj_dev_name(obj), PFID(mdo2fid(obj)), rc2);
1776         }
1777 out:
1778         mdd_trans_stop(env, mdd, rc, handle);
1779         mdd_write_unlock(env, obj);
1780         mdd_write_unlock(env, vic);
1781         lu_buf_free(buf_save);
1782         lu_buf_free(buf);
1783         lu_buf_free(buf_vic);
1784
1785         if (!rc)
1786                 (void) mdd_object_pfid_replace(env, obj);
1787
1788         return rc;
1789 }
1790
1791 static int mdd_layout_merge_allowed(const struct lu_env *env,
1792                                     struct md_object *target,
1793                                     struct md_object *victim)
1794 {
1795         struct mdd_object *o1 = md2mdd_obj(target);
1796
1797         /* cannot extend directory's LOVEA */
1798         if (S_ISDIR(mdd_object_type(o1))) {
1799                 CERROR("%s: Don't extend directory's LOVEA, just set it.\n",
1800                        mdd_obj_dev_name(o1));
1801                 RETURN(-EISDIR);
1802         }
1803
1804         RETURN(0);
1805 }
1806
1807 /**
1808  * The caller should guarantee to update the object ctime
1809  * after xattr_set if needed.
1810  */
1811 static int mdd_xattr_set(const struct lu_env *env, struct md_object *obj,
1812                          const struct lu_buf *buf, const char *name,
1813                          int fl)
1814 {
1815         struct mdd_object       *mdd_obj = md2mdd_obj(obj);
1816         struct lu_attr          *attr = MDD_ENV_VAR(env, cattr);
1817         struct mdd_device       *mdd = mdo2mdd(obj);
1818         struct thandle          *handle;
1819         enum changelog_rec_type  cl_type;
1820         int                      cl_flags = 0;
1821         int                      rc;
1822         ENTRY;
1823
1824         rc = mdd_la_get(env, mdd_obj, attr);
1825         if (rc)
1826                 RETURN(rc);
1827
1828         rc = mdd_xattr_sanity_check(env, mdd_obj, attr, name);
1829         if (rc)
1830                 RETURN(rc);
1831
1832         if (strcmp(name, XATTR_LUSTRE_LOV) == 0 &&
1833             (fl == LU_XATTR_MERGE || fl == LU_XATTR_SPLIT)) {
1834                 struct md_rejig_data *mrd = buf->lb_buf;
1835                 struct md_object *victim = mrd->mrd_obj;
1836
1837                 if (buf->lb_len != sizeof(*mrd))
1838                         RETURN(-EINVAL);
1839
1840                 rc = mdd_layout_merge_allowed(env, obj, victim);
1841                 if (rc)
1842                         RETURN(rc);
1843
1844                 if (fl == LU_XATTR_MERGE)
1845                         /* merge layout of victim as a mirror of obj's. */
1846                         rc = mdd_xattr_merge(env, obj, victim);
1847                 else
1848                         rc = mdd_xattr_split(env, obj, mrd);
1849                 RETURN(rc);
1850         }
1851
1852         if (strcmp(name, XATTR_NAME_ACL_ACCESS) == 0 ||
1853             strcmp(name, XATTR_NAME_ACL_DEFAULT) == 0) {
1854                 struct posix_acl *acl;
1855
1856                 /* user may set empty ACL, which should be treated as removing
1857                  * ACL. */
1858                 acl = posix_acl_from_xattr(&init_user_ns, buf->lb_buf,
1859                                            buf->lb_len);
1860                 if (IS_ERR(acl))
1861                         RETURN(PTR_ERR(acl));
1862                 if (acl == NULL) {
1863                         rc = mdd_xattr_del(env, obj, name);
1864                         RETURN(rc);
1865                 }
1866                 posix_acl_release(acl);
1867         }
1868
1869         if (!strcmp(name, XATTR_NAME_ACL_ACCESS)) {
1870                 rc = mdd_acl_set(env, mdd_obj, attr, buf, fl);
1871                 RETURN(rc);
1872         }
1873
1874         handle = mdd_trans_create(env, mdd);
1875         if (IS_ERR(handle))
1876                 RETURN(PTR_ERR(handle));
1877
1878         rc = mdd_declare_xattr_set(env, mdd, mdd_obj, buf, name, fl, handle);
1879         if (rc)
1880                 GOTO(stop, rc);
1881
1882         rc = mdd_trans_start(env, mdd, handle);
1883         if (rc)
1884                 GOTO(stop, rc);
1885
1886         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
1887
1888         if (strcmp(XATTR_NAME_HSM, name) == 0) {
1889                 rc = mdd_hsm_update_locked(env, obj, buf, handle, &cl_flags);
1890                 if (rc) {
1891                         mdd_write_unlock(env, mdd_obj);
1892                         GOTO(stop, rc);
1893                 }
1894         }
1895
1896         rc = mdo_xattr_set(env, mdd_obj, buf, name, fl, handle);
1897         mdd_write_unlock(env, mdd_obj);
1898         if (rc)
1899                 GOTO(stop, rc);
1900
1901         cl_type = mdd_xattr_changelog_type(env, mdd, name);
1902         if (cl_type < 0)
1903                 GOTO(stop, rc = 0);
1904
1905         rc = mdd_changelog_data_store_xattr(env, mdd, cl_type, cl_flags,
1906                                             mdd_obj, name, handle);
1907
1908         EXIT;
1909 stop:
1910         return mdd_trans_stop(env, mdd, rc, handle);
1911 }
1912
1913 static int mdd_declare_xattr_del(const struct lu_env *env,
1914                                  struct mdd_device *mdd,
1915                                  struct mdd_object *obj,
1916                                  const char *name,
1917                                  struct thandle *handle)
1918 {
1919         enum changelog_rec_type type;
1920         int rc;
1921
1922         rc = mdo_declare_xattr_del(env, obj, name, handle);
1923         if (rc)
1924                 return rc;
1925
1926         type = mdd_xattr_changelog_type(env, mdd, name);
1927         if (type < 0)
1928                 return 0; /* no changelog to store */
1929
1930         return mdd_declare_changelog_store(env, mdd, type, NULL, NULL, handle);
1931 }
1932
1933 /**
1934  * The caller should guarantee to update the object ctime
1935  * after xattr_set if needed.
1936  */
1937 static int mdd_xattr_del(const struct lu_env *env, struct md_object *obj,
1938                          const char *name)
1939 {
1940         struct mdd_object *mdd_obj = md2mdd_obj(obj);
1941         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
1942         struct mdd_device *mdd = mdo2mdd(obj);
1943         struct thandle *handle;
1944         int rc;
1945         ENTRY;
1946
1947         rc = mdd_la_get(env, mdd_obj, attr);
1948         if (rc)
1949                 RETURN(rc);
1950
1951         rc = mdd_xattr_sanity_check(env, mdd_obj, attr, name);
1952         if (rc)
1953                 RETURN(rc);
1954
1955         handle = mdd_trans_create(env, mdd);
1956         if (IS_ERR(handle))
1957                 RETURN(PTR_ERR(handle));
1958
1959         rc = mdd_declare_xattr_del(env, mdd, mdd_obj, name, handle);
1960         if (rc)
1961                 GOTO(stop, rc);
1962
1963         rc = mdd_trans_start(env, mdd, handle);
1964         if (rc)
1965                 GOTO(stop, rc);
1966
1967         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
1968         rc = mdo_xattr_del(env, mdd_obj, name, handle);
1969         mdd_write_unlock(env, mdd_obj);
1970         if (rc)
1971                 GOTO(stop, rc);
1972
1973         if (mdd_xattr_changelog_type(env, mdd, name) < 0)
1974                 GOTO(stop, rc = 0);
1975
1976         rc = mdd_changelog_data_store_xattr(env, mdd, CL_SETXATTR, 0, mdd_obj,
1977                                             name, handle);
1978
1979         EXIT;
1980 stop:
1981         return mdd_trans_stop(env, mdd, rc, handle);
1982 }
1983
1984 /*
1985  * read lov EA of an object
1986  * return the lov EA in an allocated lu_buf
1987  */
1988 int mdd_get_lov_ea(const struct lu_env *env, struct mdd_object *obj,
1989                    struct lu_buf *lmm_buf)
1990 {
1991         struct lu_buf   *buf = &mdd_env_info(env)->mti_big_buf;
1992         int              rc, bufsize;
1993         ENTRY;
1994
1995 repeat:
1996         rc = mdo_xattr_get(env, obj, buf, XATTR_NAME_LOV);
1997
1998         if (rc == -ERANGE) {
1999                 /* mti_big_buf is allocated but is too small
2000                  * we need to increase it */
2001                 buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf,
2002                                              buf->lb_len * 2);
2003                 if (buf->lb_buf == NULL)
2004                         GOTO(out, rc = -ENOMEM);
2005                 goto repeat;
2006         }
2007
2008         if (rc < 0)
2009                 RETURN(rc);
2010
2011         if (rc == 0)
2012                 RETURN(-ENODATA);
2013
2014         bufsize = rc;
2015         if (memcmp(buf, &LU_BUF_NULL, sizeof(*buf)) == 0) {
2016                 /* mti_big_buf was not allocated, so we have to
2017                  * allocate it based on the ea size */
2018                 buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf,
2019                                              bufsize);
2020                 if (buf->lb_buf == NULL)
2021                         GOTO(out, rc = -ENOMEM);
2022                 goto repeat;
2023         }
2024
2025         lu_buf_alloc(lmm_buf, bufsize);
2026         if (lmm_buf->lb_buf == NULL)
2027                 GOTO(out, rc = -ENOMEM);
2028
2029         memcpy(lmm_buf->lb_buf, buf->lb_buf, bufsize);
2030         rc = 0;
2031         EXIT;
2032
2033 out:
2034         if (rc < 0)
2035                 lu_buf_free(lmm_buf);
2036         return rc;
2037 }
2038
2039 static int mdd_xattr_hsm_replace(const struct lu_env *env,
2040                                  struct mdd_object *o, struct lu_buf *buf,
2041                                  struct thandle *handle)
2042 {
2043         struct hsm_attrs *attrs;
2044         __u32 hsm_flags;
2045         int flags = 0;
2046         int rc;
2047         ENTRY;
2048
2049         rc = mdo_xattr_set(env, o, buf, XATTR_NAME_HSM, LU_XATTR_REPLACE,
2050                            handle);
2051         if (rc != 0)
2052                 RETURN(rc);
2053
2054         attrs = buf->lb_buf;
2055         hsm_flags = le32_to_cpu(attrs->hsm_flags);
2056         if (!(hsm_flags & HS_RELEASED) || mdd_is_dead_obj(o))
2057                 RETURN(0);
2058
2059         /* Add a changelog record for release. */
2060         hsm_set_cl_event(&flags, HE_RELEASE);
2061         rc = mdd_changelog_data_store(env, mdo2mdd(&o->mod_obj), CL_HSM,
2062                                       flags, o, handle);
2063         RETURN(rc);
2064 }
2065
2066 /*
2067  *  check if layout swapping between 2 objects is allowed
2068  *  the rules are:
2069  *  - only normal FIDs or non-system IGIFs
2070  *  - same type of objects
2071  *  - same owner/group (so quotas are still valid) unless this is from HSM
2072  *    release.
2073  */
2074 static int mdd_layout_swap_allowed(const struct lu_env *env,
2075                                    struct mdd_object *o1,
2076                                    const struct lu_attr *attr1,
2077                                    struct mdd_object *o2,
2078                                    const struct lu_attr *attr2,
2079                                    __u64 flags)
2080 {
2081         const struct lu_fid     *fid1, *fid2;
2082         ENTRY;
2083
2084         fid1 = mdo2fid(o1);
2085         fid2 = mdo2fid(o2);
2086
2087         if (!fid_is_norm(fid1) &&
2088             (!fid_is_igif(fid1) || IS_ERR(mdd_links_get(env, o1))))
2089                 RETURN(-EBADF);
2090
2091         if (!fid_is_norm(fid2) &&
2092             (!fid_is_igif(fid2) || IS_ERR(mdd_links_get(env, o2))))
2093                 RETURN(-EBADF);
2094
2095         if (mdd_object_type(o1) != mdd_object_type(o2)) {
2096                 if (S_ISDIR(mdd_object_type(o1)))
2097                         RETURN(-ENOTDIR);
2098                 if (S_ISREG(mdd_object_type(o1)))
2099                         RETURN(-EISDIR);
2100                 RETURN(-EBADF);
2101         }
2102
2103         if (flags & SWAP_LAYOUTS_MDS_HSM)
2104                 RETURN(0);
2105
2106         if ((attr1->la_uid != attr2->la_uid) ||
2107             (attr1->la_gid != attr2->la_gid))
2108                 RETURN(-EPERM);
2109
2110         RETURN(0);
2111 }
2112
2113 /* XXX To set the proper lmm_oi & lmm_layout_gen when swap layouts, we have to
2114  *     look into the layout in MDD layer. */
2115 static int mdd_lmm_oi(struct lov_mds_md *lmm, struct ost_id *oi, bool get)
2116 {
2117         struct lov_comp_md_v1   *comp_v1;
2118         struct lov_mds_md       *v1;
2119         int                      i, ent_count;
2120         __u32                    off;
2121
2122         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_COMP_V1) {
2123                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
2124                 ent_count = le16_to_cpu(comp_v1->lcm_entry_count);
2125
2126                 if (ent_count == 0)
2127                         return -EINVAL;
2128
2129                 if (get) {
2130                         off = le32_to_cpu(comp_v1->lcm_entries[0].lcme_offset);
2131                         v1 = (struct lov_mds_md *)((char *)comp_v1 + off);
2132                         *oi = v1->lmm_oi;
2133                 } else {
2134                         for (i = 0; i < le32_to_cpu(ent_count); i++) {
2135                                 off = le32_to_cpu(comp_v1->lcm_entries[i].
2136                                                 lcme_offset);
2137                                 v1 = (struct lov_mds_md *)((char *)comp_v1 +
2138                                                 off);
2139                                 v1->lmm_oi = *oi;
2140                         }
2141                 }
2142         } else if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V1 ||
2143                    le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V3) {
2144                 if (get)
2145                         *oi = lmm->lmm_oi;
2146                 else
2147                         lmm->lmm_oi = *oi;
2148         } else {
2149                 return -EINVAL;
2150         }
2151         return 0;
2152 }
2153
2154 static inline int mdd_get_lmm_oi(struct lov_mds_md *lmm, struct ost_id *oi)
2155 {
2156         return mdd_lmm_oi(lmm, oi, true);
2157 }
2158
2159 static inline int mdd_set_lmm_oi(struct lov_mds_md *lmm, struct ost_id *oi)
2160 {
2161         return mdd_lmm_oi(lmm, oi, false);
2162 }
2163
2164 static int mdd_lmm_gen(struct lov_mds_md *lmm, __u32 *gen, bool get)
2165 {
2166         struct lov_comp_md_v1 *comp_v1;
2167
2168         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_COMP_V1) {
2169                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
2170                 if (get)
2171                         *gen = le32_to_cpu(comp_v1->lcm_layout_gen);
2172                 else
2173                         comp_v1->lcm_layout_gen = cpu_to_le32(*gen);
2174         } else if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V1 ||
2175                    le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V3) {
2176                 __u16 tmp_gen = *gen;
2177                 if (get)
2178                         *gen = le16_to_cpu(lmm->lmm_layout_gen);
2179                 else
2180                         lmm->lmm_layout_gen = cpu_to_le16(tmp_gen);
2181         } else {
2182                 return -EINVAL;
2183         }
2184         return 0;
2185 }
2186
2187 static inline int mdd_get_lmm_gen(struct lov_mds_md *lmm, __u32 *gen)
2188 {
2189         return mdd_lmm_gen(lmm, gen, true);
2190 }
2191
2192 static inline int mdd_set_lmm_gen(struct lov_mds_md *lmm, __u32 *gen)
2193 {
2194         return mdd_lmm_gen(lmm, gen, false);
2195 }
2196
2197 /**
2198  * swap layouts between 2 lustre objects
2199  */
2200 static int mdd_swap_layouts(const struct lu_env *env, struct md_object *obj1,
2201                             struct md_object *obj2, __u64 flags)
2202 {
2203         struct mdd_thread_info  *info = mdd_env_info(env);
2204         struct mdd_object       *fst_o = md2mdd_obj(obj1);
2205         struct mdd_object       *snd_o = md2mdd_obj(obj2);
2206         struct lu_attr          *fst_la = MDD_ENV_VAR(env, cattr);
2207         struct lu_attr          *snd_la = MDD_ENV_VAR(env, tattr);
2208         struct mdd_device       *mdd = mdo2mdd(obj1);
2209         struct lov_mds_md       *fst_lmm, *snd_lmm;
2210         struct lu_buf           *fst_buf = &info->mti_buf[0];
2211         struct lu_buf           *snd_buf = &info->mti_buf[1];
2212         struct lu_buf           *fst_hsm_buf = &info->mti_buf[2];
2213         struct lu_buf           *snd_hsm_buf = &info->mti_buf[3];
2214         struct ost_id           *saved_oi = NULL;
2215         struct thandle          *handle;
2216         __u32                    fst_gen, snd_gen, saved_gen;
2217         int                      fst_fl;
2218         int                      rc;
2219         int                      rc2;
2220         ENTRY;
2221
2222         CLASSERT(ARRAY_SIZE(info->mti_buf) >= 4);
2223         memset(info->mti_buf, 0, sizeof(info->mti_buf));
2224
2225         /* we have to sort the 2 obj, so locking will always
2226          * be in the same order, even in case of 2 concurrent swaps */
2227         rc = lu_fid_cmp(mdo2fid(fst_o), mdo2fid(snd_o));
2228         if (rc == 0) /* same fid ? */
2229                 RETURN(-EPERM);
2230
2231         if (rc < 0)
2232                 swap(fst_o, snd_o);
2233
2234         rc = mdd_la_get(env, fst_o, fst_la);
2235         if (rc != 0)
2236                 RETURN(rc);
2237
2238         rc = mdd_la_get(env, snd_o, snd_la);
2239         if (rc != 0)
2240                 RETURN(rc);
2241
2242         /* check if layout swapping is allowed */
2243         rc = mdd_layout_swap_allowed(env, fst_o, fst_la, snd_o, snd_la, flags);
2244         if (rc != 0)
2245                 RETURN(rc);
2246
2247         handle = mdd_trans_create(env, mdd);
2248         if (IS_ERR(handle))
2249                 RETURN(PTR_ERR(handle));
2250
2251         /* objects are already sorted */
2252         mdd_write_lock(env, fst_o, MOR_TGT_CHILD);
2253         mdd_write_lock(env, snd_o, MOR_TGT_CHILD);
2254
2255         rc = mdd_get_lov_ea(env, fst_o, fst_buf);
2256         if (rc < 0 && rc != -ENODATA)
2257                 GOTO(stop, rc);
2258
2259         rc = mdd_get_lov_ea(env, snd_o, snd_buf);
2260         if (rc < 0 && rc != -ENODATA)
2261                 GOTO(stop, rc);
2262
2263         /* check if file is DoM, it can be migrated only to another DoM layout
2264          * with the same DoM component size
2265          */
2266         if (mdd_lmm_dom_size(fst_buf->lb_buf) !=
2267             mdd_lmm_dom_size(snd_buf->lb_buf)) {
2268                 rc = -EOPNOTSUPP;
2269                 CDEBUG(D_LAYOUT, "cannot swap layout for "DFID": new layout "
2270                        "must have the same DoM component: rc = %d\n",
2271                        PFID(mdo2fid(fst_o)), rc);
2272                 GOTO(stop, rc);
2273         }
2274
2275         /* swapping 2 non existant layouts is a success */
2276         if (fst_buf->lb_buf == NULL && snd_buf->lb_buf == NULL)
2277                 GOTO(stop, rc = 0);
2278
2279         /* to help inode migration between MDT, it is better to
2280          * start by the no layout file (if one), so we order the swap */
2281         if (snd_buf->lb_buf == NULL) {
2282                 swap(fst_o, snd_o);
2283                 swap(fst_buf, snd_buf);
2284         }
2285
2286         fst_gen = snd_gen = 0;
2287         /* lmm and generation layout initialization */
2288         if (fst_buf->lb_buf != NULL) {
2289                 fst_lmm = fst_buf->lb_buf;
2290                 mdd_get_lmm_gen(fst_lmm, &fst_gen);
2291                 fst_fl  = LU_XATTR_REPLACE;
2292         } else {
2293                 fst_lmm = NULL;
2294                 fst_gen = 0;
2295                 fst_fl  = LU_XATTR_CREATE;
2296         }
2297
2298         snd_lmm = snd_buf->lb_buf;
2299         mdd_get_lmm_gen(snd_lmm, &snd_gen);
2300
2301         saved_gen = fst_gen;
2302         /* increase the generation layout numbers */
2303         snd_gen++;
2304         fst_gen++;
2305
2306         /*
2307          * XXX The layout generation is used to generate component IDs for
2308          *     the composite file, we have to do some special tweaks to make
2309          *     sure the layout generation is always adequate for that job.
2310          */
2311
2312         /* Skip invalid generation number for composite layout */
2313         if ((snd_gen & LCME_ID_MASK) == 0)
2314                 snd_gen++;
2315         if ((fst_gen & LCME_ID_MASK) == 0)
2316                 fst_gen++;
2317         /* Make sure the generation is greater than all the component IDs */
2318         if (fst_gen < snd_gen)
2319                 fst_gen = snd_gen;
2320         else if (fst_gen > snd_gen)
2321                 snd_gen = fst_gen;
2322
2323         /* set the file specific informations in lmm */
2324         if (fst_lmm != NULL) {
2325                 saved_oi = &info->mti_oa.o_oi;
2326                 mdd_get_lmm_oi(fst_lmm, saved_oi);
2327                 mdd_set_lmm_gen(fst_lmm, &snd_gen);
2328                 mdd_set_lmm_oi(fst_lmm, &snd_lmm->lmm_oi);
2329                 mdd_set_lmm_oi(snd_lmm, saved_oi);
2330         } else {
2331                 if ((snd_lmm->lmm_magic & cpu_to_le32(LOV_MAGIC_MASK)) ==
2332                     cpu_to_le32(LOV_MAGIC_MAGIC))
2333                         snd_lmm->lmm_magic |= cpu_to_le32(LOV_MAGIC_DEFINED);
2334                 else
2335                         GOTO(stop, rc = -EPROTO);
2336         }
2337         mdd_set_lmm_gen(snd_lmm, &fst_gen);
2338
2339         /* Prepare HSM attribute if it's required */
2340         if (flags & SWAP_LAYOUTS_MDS_HSM) {
2341                 const int buflen = sizeof(struct hsm_attrs);
2342
2343                 lu_buf_alloc(fst_hsm_buf, buflen);
2344                 lu_buf_alloc(snd_hsm_buf, buflen);
2345                 if (fst_hsm_buf->lb_buf == NULL || snd_hsm_buf->lb_buf == NULL)
2346                         GOTO(stop, rc = -ENOMEM);
2347
2348                 /* Read HSM attribute */
2349                 rc = mdo_xattr_get(env, fst_o, fst_hsm_buf, XATTR_NAME_HSM);
2350                 if (rc < 0)
2351                         GOTO(stop, rc);
2352
2353                 rc = mdo_xattr_get(env, snd_o, snd_hsm_buf, XATTR_NAME_HSM);
2354                 if (rc < 0)
2355                         GOTO(stop, rc);
2356
2357                 rc = mdd_declare_xattr_set(env, mdd, fst_o, snd_hsm_buf,
2358                                            XATTR_NAME_HSM, LU_XATTR_REPLACE,
2359                                            handle);
2360                 if (rc < 0)
2361                         GOTO(stop, rc);
2362
2363                 rc = mdd_declare_xattr_set(env, mdd, snd_o, fst_hsm_buf,
2364                                            XATTR_NAME_HSM, LU_XATTR_REPLACE,
2365                                            handle);
2366                 if (rc < 0)
2367                         GOTO(stop, rc);
2368         }
2369
2370         /* prepare transaction */
2371         rc = mdd_declare_xattr_set(env, mdd, fst_o, snd_buf, XATTR_NAME_LOV,
2372                                    fst_fl, handle);
2373         if (rc != 0)
2374                 GOTO(stop, rc);
2375
2376         if (fst_buf->lb_buf != NULL)
2377                 rc = mdd_declare_xattr_set(env, mdd, snd_o, fst_buf,
2378                                            XATTR_NAME_LOV, LU_XATTR_REPLACE,
2379                                            handle);
2380         else
2381                 rc = mdd_declare_xattr_del(env, mdd, snd_o, XATTR_NAME_LOV,
2382                                            handle);
2383         if (rc != 0)
2384                 GOTO(stop, rc);
2385
2386         rc = mdd_trans_start(env, mdd, handle);
2387         if (rc != 0)
2388                 GOTO(stop, rc);
2389
2390         if (flags & SWAP_LAYOUTS_MDS_HSM) {
2391                 rc = mdd_xattr_hsm_replace(env, fst_o, snd_hsm_buf, handle);
2392                 if (rc < 0)
2393                         GOTO(stop, rc);
2394
2395                 rc = mdd_xattr_hsm_replace(env, snd_o, fst_hsm_buf, handle);
2396                 if (rc < 0) {
2397                         rc2 = mdd_xattr_hsm_replace(env, fst_o, fst_hsm_buf,
2398                                                     handle);
2399                         if (rc2 < 0)
2400                                 CERROR("%s: restore "DFID" HSM error: %d/%d\n",
2401                                        mdd_obj_dev_name(fst_o),
2402                                        PFID(mdo2fid(fst_o)), rc, rc2);
2403                         GOTO(stop, rc);
2404                 }
2405         }
2406
2407         rc = mdo_xattr_set(env, fst_o, snd_buf, XATTR_NAME_LOV, fst_fl, handle);
2408         if (rc != 0)
2409                 GOTO(stop, rc);
2410
2411         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_MDS_HSM_SWAP_LAYOUTS))) {
2412                 rc = -EOPNOTSUPP;
2413         } else {
2414                 if (fst_buf->lb_buf != NULL)
2415                         rc = mdo_xattr_set(env, snd_o, fst_buf, XATTR_NAME_LOV,
2416                                            LU_XATTR_REPLACE, handle);
2417                 else
2418                         rc = mdo_xattr_del(env, snd_o, XATTR_NAME_LOV, handle);
2419         }
2420         if (rc != 0)
2421                 GOTO(out_restore, rc);
2422
2423         /* Issue one changelog record per file */
2424         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, fst_o, handle);
2425         if (rc)
2426                 GOTO(stop, rc);
2427
2428         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, snd_o, handle);
2429         if (rc)
2430                 GOTO(stop, rc);
2431         EXIT;
2432
2433 out_restore:
2434         if (rc != 0) {
2435                 int steps = 0;
2436
2437                 /* failure on second file, but first was done, so we have
2438                  * to roll back first. */
2439                 if (fst_buf->lb_buf != NULL) {
2440                         mdd_set_lmm_oi(fst_lmm, saved_oi);
2441                         mdd_set_lmm_gen(fst_lmm, &saved_gen);
2442                         rc2 = mdo_xattr_set(env, fst_o, fst_buf, XATTR_NAME_LOV,
2443                                             LU_XATTR_REPLACE, handle);
2444                 } else {
2445                         rc2 = mdo_xattr_del(env, fst_o, XATTR_NAME_LOV, handle);
2446                 }
2447                 if (rc2 < 0)
2448                         goto do_lbug;
2449
2450                 ++steps;
2451                 rc2 = mdd_xattr_hsm_replace(env, fst_o, fst_hsm_buf, handle);
2452                 if (rc2 < 0)
2453                         goto do_lbug;
2454
2455                 ++steps;
2456                 rc2 = mdd_xattr_hsm_replace(env, snd_o, snd_hsm_buf, handle);
2457
2458         do_lbug:
2459                 if (rc2 < 0) {
2460                         /* very bad day */
2461                         CERROR("%s: unable to roll back layout swap. FIDs: "
2462                                DFID" and "DFID "error: %d/%d, steps: %d\n",
2463                                mdd_obj_dev_name(fst_o),
2464                                PFID(mdo2fid(snd_o)), PFID(mdo2fid(fst_o)),
2465                                rc, rc2, steps);
2466                         /* a solution to avoid journal commit is to panic,
2467                          * but it has strong consequences so we use LBUG to
2468                          * allow sysdamin to choose to panic or not
2469                          */
2470                         LBUG();
2471                 }
2472         }
2473
2474 stop:
2475         rc = mdd_trans_stop(env, mdd, rc, handle);
2476
2477         mdd_write_unlock(env, snd_o);
2478         mdd_write_unlock(env, fst_o);
2479
2480         lu_buf_free(fst_buf);
2481         lu_buf_free(snd_buf);
2482         lu_buf_free(fst_hsm_buf);
2483         lu_buf_free(snd_hsm_buf);
2484
2485         if (!rc) {
2486                 (void) mdd_object_pfid_replace(env, fst_o);
2487                 (void) mdd_object_pfid_replace(env, snd_o);
2488         }
2489         return rc;
2490 }
2491
2492 static int mdd_declare_layout_change(const struct lu_env *env,
2493                                      struct mdd_device *mdd,
2494                                      struct mdd_object *obj,
2495                                      struct md_layout_change *mlc,
2496                                      struct thandle *handle)
2497 {
2498         int rc;
2499
2500         rc = mdo_declare_layout_change(env, obj, mlc, handle);
2501         if (rc)
2502                 return rc;
2503
2504         return mdd_declare_changelog_store(env, mdd, CL_LAYOUT, NULL, NULL,
2505                                            handle);
2506 }
2507
2508 /* For PFL, this is used to instantiate necessary component objects. */
2509 static int
2510 mdd_layout_instantiate_component(const struct lu_env *env,
2511                 struct mdd_object *obj, struct md_layout_change *mlc,
2512                 struct thandle *handle)
2513 {
2514         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
2515         int rc;
2516         ENTRY;
2517
2518         if (mlc->mlc_opc != MD_LAYOUT_WRITE)
2519                 RETURN(-ENOTSUPP);
2520
2521         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2522         /**
2523          * It's possible that another layout write intent has already
2524          * instantiated our objects, so a -EALREADY returned, and we need to
2525          * do nothing.
2526          */
2527         if (rc)
2528                 RETURN(rc == -EALREADY ? 0 : rc);
2529
2530         rc = mdd_trans_start(env, mdd, handle);
2531         if (rc)
2532                 RETURN(rc);
2533
2534         mdd_write_lock(env, obj, MOR_TGT_CHILD);
2535         rc = mdo_layout_change(env, obj, mlc, handle);
2536         mdd_write_unlock(env, obj);
2537         if (rc)
2538                 RETURN(rc);
2539
2540         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, obj, handle);
2541         RETURN(rc);
2542 }
2543
2544 /**
2545  * Change the FLR layout from RDONLY to WRITE_PENDING.
2546  *
2547  * It picks the primary mirror, and bumps the layout version, and set
2548  * layout version xattr to OST objects in a sync tx. In order to facilitate
2549  * the handling of phantom writers from evicted clients, the clients carry
2550  * layout version of the file with write RPC, so that the OSTs can verify
2551  * if the write RPCs are legitimate, meaning not from evicted clients.
2552  */
2553 static int
2554 mdd_layout_update_rdonly(const struct lu_env *env, struct mdd_object *obj,
2555                          struct md_layout_change *mlc, struct thandle *handle)
2556 {
2557         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
2558         struct lu_buf *som_buf = &mdd_env_info(env)->mti_buf[1];
2559         struct lustre_som_attrs *som = &mlc->mlc_som;
2560         int fl = 0;
2561         int rc;
2562         ENTRY;
2563
2564         /* Verify acceptable operations */
2565         switch (mlc->mlc_opc) {
2566         case MD_LAYOUT_WRITE:
2567         case MD_LAYOUT_RESYNC:
2568                 /* these are legal operations - this represents the case that
2569                  * a few mirrors were missed in the last resync. */
2570                 break;
2571         case MD_LAYOUT_RESYNC_DONE:
2572         default:
2573                 RETURN(0);
2574         }
2575
2576         som_buf->lb_buf = som;
2577         som_buf->lb_len = sizeof(*som);
2578         rc = mdo_xattr_get(env, obj, som_buf, XATTR_NAME_SOM);
2579         if (rc < 0 && rc != -ENODATA)
2580                 RETURN(rc);
2581
2582         if (rc > 0) {
2583                 lustre_som_swab(som);
2584                 if (som->lsa_valid & SOM_FL_STRICT)
2585                         fl = LU_XATTR_REPLACE;
2586         }
2587
2588         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2589         if (rc)
2590                 GOTO(out, rc);
2591
2592         if (fl) {
2593                 rc = mdd_declare_xattr_set(env, mdd, obj, som_buf,
2594                                            XATTR_NAME_SOM, fl, handle);
2595                 if (rc)
2596                         GOTO(out, rc);
2597         }
2598
2599         /* record a changelog for data mover to consume */
2600         rc = mdd_declare_changelog_store(env, mdd, CL_FLRW, NULL, NULL, handle);
2601         if (rc)
2602                 GOTO(out, rc);
2603
2604         rc = mdd_trans_start(env, mdd, handle);
2605         if (rc)
2606                 GOTO(out, rc);
2607
2608         /* it needs a sync tx to make FLR to work properly */
2609         handle->th_sync = 1;
2610
2611         mdd_write_lock(env, obj, MOR_TGT_CHILD);
2612         rc = mdo_layout_change(env, obj, mlc, handle);
2613         if (!rc && fl) {
2614                 /* SOM state transition from STRICT to STALE */
2615                 som->lsa_valid = SOM_FL_STALE;
2616                 lustre_som_swab(som);
2617                 rc = mdo_xattr_set(env, obj, som_buf, XATTR_NAME_SOM,
2618                                    fl, handle);
2619         }
2620         mdd_write_unlock(env, obj);
2621         if (rc)
2622                 GOTO(out, rc);
2623
2624         rc = mdd_changelog_data_store(env, mdd, CL_FLRW, 0, obj, handle);
2625         if (rc)
2626                 GOTO(out, rc);
2627
2628         EXIT;
2629
2630 out:
2631         return rc;
2632 }
2633
2634 /**
2635  * Handle mirrored file state transition when it's in WRITE_PENDING.
2636  *
2637  * Only MD_LAYOUT_RESYNC, which represents start of resync, is allowed when
2638  * the file is in WRITE_PENDING state. If everything goes fine, the file's
2639  * layout version will be increased, and the file's state will be changed to
2640  * SYNC_PENDING.
2641  */
2642 static int
2643 mdd_layout_update_write_pending(const struct lu_env *env,
2644                 struct mdd_object *obj, struct md_layout_change *mlc,
2645                 struct thandle *handle)
2646 {
2647         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
2648         int rc;
2649         ENTRY;
2650
2651         switch (mlc->mlc_opc) {
2652         case MD_LAYOUT_RESYNC:
2653                 /* Upon receiving the resync request, it should
2654                  * instantiate all stale components right away to get ready
2655                  * for mirror copy. In order to avoid layout version change,
2656                  * client should avoid sending LAYOUT_WRITE request at the
2657                  * resync state. */
2658                 break;
2659         case MD_LAYOUT_WRITE:
2660                 /* legal race for concurrent write, the file state has been
2661                  * changed by another client. */
2662                 break;
2663         default:
2664                 RETURN(-EBUSY);
2665         }
2666
2667         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2668         if (rc)
2669                 GOTO(out, rc);
2670
2671         rc = mdd_trans_start(env, mdd, handle);
2672         if (rc)
2673                 GOTO(out, rc);
2674
2675         /* it needs a sync tx to make FLR to work properly */
2676         handle->th_sync = 1;
2677
2678         mdd_write_lock(env, obj, MOR_TGT_CHILD);
2679         rc = mdo_layout_change(env, obj, mlc, handle);
2680         mdd_write_unlock(env, obj);
2681         if (rc)
2682                 GOTO(out, rc);
2683
2684         EXIT;
2685
2686 out:
2687         return rc;
2688 }
2689
2690 /**
2691  * Handle the requests when a FLR file's state is in SYNC_PENDING.
2692  *
2693  * Only concurrent write and sync complete requests are possible when the
2694  * file is in SYNC_PENDING. For the latter request, it will pass in the
2695  * mirrors that have been synchronized, then the stale bit will be cleared
2696  * to make the file's state turn into RDONLY.
2697  * For concurrent write reqeust, it just needs to change the file's state
2698  * to WRITE_PENDING in a sync tx. It doesn't have to change the layout
2699  * version because the version will be increased in the transition to
2700  * SYNC_PENDING later so that it can deny the write request from potential
2701  * evicted SYNC clients. */
2702 static int
2703 mdd_object_update_sync_pending(const struct lu_env *env, struct mdd_object *obj,
2704                 struct md_layout_change *mlc, struct thandle *handle)
2705 {
2706         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
2707         struct lu_buf *som_buf = &mdd_env_info(env)->mti_buf[1];
2708         int fl = 0;
2709         int rc;
2710         ENTRY;
2711
2712         /* operation validation */
2713         switch (mlc->mlc_opc) {
2714         case MD_LAYOUT_RESYNC_DONE:
2715                 /* resync complete. */
2716         case MD_LAYOUT_WRITE:
2717                 /* concurrent write. */
2718                 break;
2719         case MD_LAYOUT_RESYNC:
2720                 /* resync again, most likely the previous run failed.
2721                  * no-op if it's already in SYNC_PENDING state */
2722                 RETURN(0);
2723         default:
2724                 RETURN(-EBUSY);
2725         }
2726
2727         if (mlc->mlc_som.lsa_valid & SOM_FL_STRICT) {
2728                 rc = mdo_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_SOM);
2729                 if (rc < 0 && rc != -ENODATA)
2730                         RETURN(rc);
2731
2732                 fl = rc == -ENODATA ? LU_XATTR_CREATE : LU_XATTR_REPLACE;
2733                 lustre_som_swab(&mlc->mlc_som);
2734                 som_buf->lb_buf = &mlc->mlc_som;
2735                 som_buf->lb_len = sizeof(mlc->mlc_som);
2736         }
2737
2738         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2739         if (rc)
2740                 GOTO(out, rc);
2741
2742         /* record a changelog for the completion of resync */
2743         rc = mdd_declare_changelog_store(env, mdd, CL_RESYNC, NULL, NULL,
2744                                          handle);
2745         if (rc)
2746                 GOTO(out, rc);
2747
2748         /* RESYNC_DONE has piggybacked size and blocks */
2749         if (fl) {
2750                 rc = mdd_declare_xattr_set(env, mdd, obj, som_buf,
2751                                            XATTR_NAME_SOM, fl, handle);
2752                 if (rc)
2753                         GOTO(out, rc);
2754         }
2755
2756         rc = mdd_trans_start(env, mdd, handle);
2757         if (rc)
2758                 GOTO(out, rc);
2759
2760         /* it needs a sync tx to make FLR to work properly */
2761         handle->th_sync = 1;
2762
2763         rc = mdo_layout_change(env, obj, mlc, handle);
2764         if (rc)
2765                 GOTO(out, rc);
2766
2767         if (fl) {
2768                 rc = mdo_xattr_set(env, obj, som_buf, XATTR_NAME_SOM,
2769                                    fl, handle);
2770                 if (rc)
2771                         GOTO(out, rc);
2772         }
2773
2774         rc = mdd_changelog_data_store(env, mdd, CL_RESYNC, 0, obj, handle);
2775         if (rc)
2776                 GOTO(out, rc);
2777         EXIT;
2778 out:
2779         return rc;
2780 }
2781
2782 /**
2783  * Layout change callback for object.
2784  *
2785  * This is only used by FLR for now. In the future, it can be exteneded to
2786  * handle all layout change.
2787  */
2788 static int
2789 mdd_layout_change(const struct lu_env *env, struct md_object *o,
2790                   struct md_layout_change *mlc)
2791 {
2792         struct mdd_object       *obj = md2mdd_obj(o);
2793         struct mdd_device       *mdd = mdd_obj2mdd_dev(obj);
2794         struct lu_buf           *buf = mdd_buf_get(env, NULL, 0);
2795         struct lov_comp_md_v1   *lcm;
2796         struct thandle          *handle;
2797         int flr_state;
2798         int rc;
2799         ENTRY;
2800
2801         /* Verify acceptable operations */
2802         switch (mlc->mlc_opc) {
2803         case MD_LAYOUT_WRITE:
2804         case MD_LAYOUT_RESYNC:
2805         case MD_LAYOUT_RESYNC_DONE:
2806                 break;
2807         default:
2808                 RETURN(-ENOTSUPP);
2809         }
2810
2811         handle = mdd_trans_create(env, mdd);
2812         if (IS_ERR(handle))
2813                 RETURN(PTR_ERR(handle));
2814
2815         rc = mdd_get_lov_ea(env, obj, buf);
2816         if (rc < 0) {
2817                 if (rc == -ENODATA)
2818                         rc = -EINVAL;
2819                 GOTO(out, rc);
2820         }
2821
2822         /* analyze the layout to make sure it's a FLR file */
2823         lcm = buf->lb_buf;
2824         if (le32_to_cpu(lcm->lcm_magic) != LOV_MAGIC_COMP_V1)
2825                 GOTO(out, rc = -EINVAL);
2826
2827         flr_state = le16_to_cpu(lcm->lcm_flags) & LCM_FL_FLR_MASK;
2828
2829         /* please refer to HLD of FLR for state transition */
2830         switch (flr_state) {
2831         case LCM_FL_NONE:
2832                 rc = mdd_layout_instantiate_component(env, obj, mlc, handle);
2833                 break;
2834         case LCM_FL_WRITE_PENDING:
2835                 rc = mdd_layout_update_write_pending(env, obj, mlc, handle);
2836                 break;
2837         case LCM_FL_RDONLY:
2838                 rc = mdd_layout_update_rdonly(env, obj, mlc, handle);
2839                 break;
2840         case LCM_FL_SYNC_PENDING:
2841                 rc = mdd_object_update_sync_pending(env, obj, mlc, handle);
2842                 break;
2843         default:
2844                 rc = 0;
2845                 break;
2846         }
2847         EXIT;
2848
2849 out:
2850         mdd_trans_stop(env, mdd, rc, handle);
2851         lu_buf_free(buf);
2852         return rc;
2853 }
2854
2855 void mdd_object_make_hint(const struct lu_env *env, struct mdd_object *parent,
2856                           struct mdd_object *child, const struct lu_attr *attr,
2857                           const struct md_op_spec *spec,
2858                           struct dt_allocation_hint *hint)
2859 {
2860         struct dt_object *np = parent ?  mdd_object_child(parent) : NULL;
2861         struct dt_object *nc = mdd_object_child(child);
2862
2863         memset(hint, 0, sizeof(*hint));
2864
2865         /* For striped directory, give striping EA to lod_ah_init, which will
2866          * decide the stripe_offset and stripe count by it. */
2867         if (S_ISDIR(attr->la_mode) &&
2868             unlikely(spec != NULL && spec->sp_cr_flags & MDS_OPEN_HAS_EA)) {
2869                 hint->dah_eadata = spec->u.sp_ea.eadata;
2870                 hint->dah_eadata_len = spec->u.sp_ea.eadatalen;
2871         } else {
2872                 hint->dah_eadata = NULL;
2873                 hint->dah_eadata_len = 0;
2874         }
2875
2876         CDEBUG(D_INFO, DFID" eadata %p len %d\n", PFID(mdd_object_fid(child)),
2877                hint->dah_eadata, hint->dah_eadata_len);
2878         /* @hint will be initialized by underlying device. */
2879         nc->do_ops->do_ah_init(env, hint, np, nc, attr->la_mode & S_IFMT);
2880 }
2881
2882 /*
2883  * do NOT or the MAY_*'s, you'll get the weakest
2884  */
2885 int accmode(const struct lu_env *env, const struct lu_attr *la, int flags)
2886 {
2887         int res = 0;
2888
2889         /* Sadly, NFSD reopens a file repeatedly during operation, so the
2890          * "acc_mode = 0" allowance for newly-created files isn't honoured.
2891          * NFSD uses the MDS_OPEN_OWNEROVERRIDE flag to say that a file
2892          * owner can write to a file even if it is marked readonly to hide
2893          * its brokenness. (bug 5781) */
2894         if (flags & MDS_OPEN_OWNEROVERRIDE) {
2895                 struct lu_ucred *uc = lu_ucred_check(env);
2896
2897                 if ((uc == NULL) || (la->la_uid == uc->uc_fsuid))
2898                         return 0;
2899         }
2900
2901         if (flags & MDS_FMODE_READ)
2902                 res |= MAY_READ;
2903         if (flags & (MDS_FMODE_WRITE | MDS_OPEN_TRUNC | MDS_OPEN_APPEND))
2904                 res |= MAY_WRITE;
2905         if (flags & MDS_FMODE_EXEC)
2906                 res = MAY_EXEC;
2907         return res;
2908 }
2909
2910 static int mdd_open_sanity_check(const struct lu_env *env,
2911                                 struct mdd_object *obj,
2912                                 const struct lu_attr *attr, int flag)
2913 {
2914         int mode, rc;
2915         ENTRY;
2916
2917         /* EEXIST check */
2918         if (mdd_is_dead_obj(obj))
2919                 RETURN(-ENOENT);
2920
2921         if (S_ISLNK(attr->la_mode))
2922                 RETURN(-ELOOP);
2923
2924         mode = accmode(env, attr, flag);
2925
2926         if (S_ISDIR(attr->la_mode) && (mode & MAY_WRITE))
2927                 RETURN(-EISDIR);
2928
2929         if (!(flag & MDS_OPEN_CREATED)) {
2930                 rc = mdd_permission_internal(env, obj, attr, mode);
2931                 if (rc)
2932                         RETURN(rc);
2933         }
2934
2935         if (S_ISFIFO(attr->la_mode) || S_ISSOCK(attr->la_mode) ||
2936             S_ISBLK(attr->la_mode) || S_ISCHR(attr->la_mode))
2937                 flag &= ~MDS_OPEN_TRUNC;
2938
2939         /* For writing append-only file must open it with append mode. */
2940         if (attr->la_flags & LUSTRE_APPEND_FL) {
2941                 if ((flag & MDS_FMODE_WRITE) && !(flag & MDS_OPEN_APPEND))
2942                         RETURN(-EPERM);
2943                 if (flag & MDS_OPEN_TRUNC)
2944                         RETURN(-EPERM);
2945         }
2946
2947         RETURN(0);
2948 }
2949
2950 static int mdd_open(const struct lu_env *env, struct md_object *obj,
2951                     int flags)
2952 {
2953         struct mdd_object *mdd_obj = md2mdd_obj(obj);
2954         struct md_device *md_dev = lu2md_dev(mdd2lu_dev(mdo2mdd(obj)));
2955         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
2956         struct mdd_object_user *mou = NULL;
2957         const struct lu_ucred *uc = lu_ucred(env);
2958         struct mdd_device *mdd = mdo2mdd(obj);
2959         enum changelog_rec_type type = CL_OPEN;
2960         int rc = 0;
2961
2962         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
2963
2964         rc = mdd_la_get(env, mdd_obj, attr);
2965         if (rc != 0)
2966                 GOTO(out, rc);
2967
2968         rc = mdd_open_sanity_check(env, mdd_obj, attr, flags);
2969         if ((rc == -EACCES) && (mdd->mdd_cl.mc_mask & (1 << CL_DN_OPEN)))
2970                 type = CL_DN_OPEN;
2971         else if (rc != 0)
2972                 GOTO(out, rc);
2973         else
2974                 mdd_obj->mod_count++;
2975
2976         if (!mdd_changelog_enabled(env, mdd, type))
2977                 GOTO(out, rc);
2978
2979 find:
2980         /* look for existing opener in list under mdd_write_lock */
2981         mou = mdd_obj_user_find(mdd_obj, uc->uc_uid, uc->uc_gid, flags);
2982
2983         if (!mou) {
2984                 int rc2;
2985
2986                 /* add user to list */
2987                 mou = mdd_obj_user_alloc(flags, uc->uc_uid, uc->uc_gid);
2988                 if (IS_ERR(mou)) {
2989                         if (rc == 0)
2990                                 rc = PTR_ERR(mou);
2991                         GOTO(out, rc);
2992                 }
2993                 rc2 = mdd_obj_user_add(mdd_obj, mou, type == CL_DN_OPEN);
2994                 if (rc2 != 0) {
2995                         mdd_obj_user_free(mou);
2996                         if (rc2 == -EEXIST)
2997                                 GOTO(find, rc2);
2998                 }
2999         } else {
3000                 if (type == CL_DN_OPEN) {
3001                         if (ktime_before(ktime_get(), mou->mou_deniednext))
3002                                 /* same user denied again same access within
3003                                  * time interval: do not record
3004                                  */
3005                                 GOTO(out, rc);
3006
3007                         /* this user already denied, but some time ago:
3008                          * update denied time
3009                          */
3010                         mou->mou_deniednext =
3011                                 ktime_add(ktime_get(),
3012                                           ktime_set(mdd->mdd_cl.mc_deniednext,
3013                                                     0));
3014                 } else {
3015                         mou->mou_opencount++;
3016                         /* same user opening file again with same flags:
3017                          * don't record
3018                          */
3019                         GOTO(out, rc);
3020                 }
3021         }
3022
3023         mdd_changelog(env, type, flags, md_dev, mdo2fid(mdd_obj));
3024
3025         EXIT;
3026 out:
3027         mdd_write_unlock(env, mdd_obj);
3028         return rc;
3029 }
3030
3031 static int mdd_declare_close(const struct lu_env *env, struct mdd_object *obj,
3032                              struct md_attr *ma, struct thandle *handle)
3033 {
3034         int rc;
3035
3036         rc = mdd_orphan_declare_delete(env, obj, handle);
3037         if (rc)
3038                 return rc;
3039
3040         return mdo_declare_destroy(env, obj, handle);
3041 }
3042
3043 /*
3044  * No permission check is needed.
3045  */
3046 static int mdd_close(const struct lu_env *env, struct md_object *obj,
3047                      struct md_attr *ma, int mode)
3048 {
3049         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3050         struct mdd_device *mdd = mdo2mdd(obj);
3051         struct thandle *handle = NULL;
3052         int is_orphan = 0;
3053         int rc;
3054         bool blocked = false;
3055         int last_close_by_uid = 0;
3056         const struct lu_ucred *uc = lu_ucred(env);
3057         ENTRY;
3058
3059         if (ma->ma_valid & MA_FLAGS && ma->ma_attr_flags & MDS_KEEP_ORPHAN) {
3060                 mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
3061                 mdd_obj->mod_count--;
3062                 mdd_write_unlock(env, mdd_obj);
3063
3064                 if (mdd_obj->mod_flags & ORPHAN_OBJ && !mdd_obj->mod_count)
3065                         CDEBUG(D_HA, "Object "DFID" is retained in orphan "
3066                                 "list\n", PFID(mdd_object_fid(mdd_obj)));
3067                 RETURN(0);
3068         }
3069
3070         /* mdd_finish_unlink() will always set orphan object as DEAD_OBJ, but
3071          * it might fail to add the object to orphan list (w/o ORPHAN_OBJ). */
3072         /* check without any lock */
3073         is_orphan = mdd_obj->mod_count == 1 &&
3074                     (mdd_obj->mod_flags & (ORPHAN_OBJ | DEAD_OBJ)) != 0;
3075
3076 again:
3077         if (is_orphan) {
3078                 /* mdd_trans_create() maybe failed because of barrier_entry(),
3079                  * under such case, the orphan MDT-object will be left in the
3080                  * orphan list, and when the MDT remount next time, the unused
3081                  * orphans will be destroyed automatically.
3082                  *
3083                  * One exception: the former mdd_finish_unlink may failed to
3084                  * add the orphan MDT-object to the orphan list, then if the
3085                  * mdd_trans_create() failed because of barrier_entry(), the
3086                  * MDT-object will become real orphan that is neither in the
3087                  * namespace nor in the orphan list. Such bad case should be
3088                  * very rare and will be handled by e2fsck/lfsck. */
3089                 handle = mdd_trans_create(env, mdo2mdd(obj));
3090                 if (IS_ERR(handle)) {
3091                         rc = PTR_ERR(handle);
3092                         if (rc != -EINPROGRESS)
3093                                 GOTO(stop, rc);
3094
3095                         handle = NULL;
3096                         blocked = true;
3097                         goto cont;
3098                 }
3099
3100                 rc = mdd_declare_close(env, mdd_obj, ma, handle);
3101                 if (rc)
3102                         GOTO(stop, rc);
3103
3104                 rc = mdd_declare_changelog_store(env, mdd, CL_CLOSE, NULL, NULL,
3105                                                  handle);
3106                 if (rc)
3107                         GOTO(stop, rc);
3108
3109                 rc = mdd_trans_start(env, mdo2mdd(obj), handle);
3110                 if (rc)
3111                         GOTO(stop, rc);
3112         }
3113
3114 cont:
3115         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
3116         rc = mdd_la_get(env, mdd_obj, &ma->ma_attr);
3117         if (rc != 0) {
3118                 CERROR("%s: failed to get lu_attr of "DFID": rc = %d\n",
3119                        lu_dev_name(mdd2lu_dev(mdd)),
3120                        PFID(mdd_object_fid(mdd_obj)), rc);
3121                 GOTO(out, rc);
3122         }
3123
3124         /* check again with lock */
3125         is_orphan = (mdd_obj->mod_count == 1) &&
3126                     ((mdd_obj->mod_flags & (ORPHAN_OBJ | DEAD_OBJ)) != 0 ||
3127                      ma->ma_attr.la_nlink == 0);
3128
3129         if (is_orphan && !handle && !blocked) {
3130                 mdd_write_unlock(env, mdd_obj);
3131                 goto again;
3132         }
3133
3134         mdd_obj->mod_count--; /*release open count */
3135
3136         /* under mdd write lock */
3137         /* If recording, see if we need to remove UID from list */
3138         if (mdd_changelog_enabled(env, mdd, CL_OPEN)) {
3139                 struct mdd_object_user *mou;
3140
3141                 /* look for UID in list */
3142                 /* If mou is NULL, it probably means logging was enabled after
3143                  * the user had the file open. So the corresponding close
3144                  * will not be logged.
3145                  */
3146                 mou = mdd_obj_user_find(mdd_obj, uc->uc_uid, uc->uc_gid, mode);
3147                 if (mou) {
3148                         mou->mou_opencount--;
3149                         if (mou->mou_opencount == 0) {
3150                                 mdd_obj_user_remove(mdd_obj, mou);
3151                                 last_close_by_uid = 1;
3152                         }
3153                 }
3154         }
3155
3156         if (!is_orphan || blocked)
3157                 GOTO(out, rc = 0);
3158
3159         /* Orphan object */
3160         /* NB: Object maybe not in orphan list originally, it is rare case for
3161          * mdd_finish_unlink() failure, in that case, the object doesn't have
3162          * ORPHAN_OBJ flag */
3163         if ((mdd_obj->mod_flags & ORPHAN_OBJ) != 0) {
3164                 /* remove link to object from orphan index */
3165                 LASSERT(handle != NULL);
3166                 rc = mdd_orphan_delete(env, mdd_obj, handle);
3167                 if (rc != 0) {
3168                         CERROR("%s: unable to delete "DFID" from orphan list: "
3169                                "rc = %d\n", lu_dev_name(mdd2lu_dev(mdd)),
3170                                PFID(mdd_object_fid(mdd_obj)), rc);
3171                         /* If object was not deleted from orphan list, do not
3172                          * destroy OSS objects, which will be done when next
3173                          * recovery. */
3174                         GOTO(out, rc);
3175                 }
3176
3177                 CDEBUG(D_HA, "Object "DFID" is deleted from orphan "
3178                        "list, OSS objects to be destroyed.\n",
3179                        PFID(mdd_object_fid(mdd_obj)));
3180         }
3181
3182         rc = mdo_destroy(env, mdd_obj, handle);
3183
3184         if (rc != 0) {
3185                 CERROR("%s: unable to delete "DFID" from orphan list: "
3186                        "rc = %d\n", lu_dev_name(mdd2lu_dev(mdd)),
3187                        PFID(mdd_object_fid(mdd_obj)), rc);
3188         }
3189         EXIT;
3190
3191 out:
3192         mdd_write_unlock(env, mdd_obj);
3193
3194         if (rc != 0 || blocked ||
3195             !mdd_changelog_enabled(env, mdd, CL_CLOSE))
3196                 GOTO(stop, rc);
3197
3198         /* Record CL_CLOSE in changelog only if file was opened in write mode,
3199          * or if CL_OPEN was recorded and it's last close by user.
3200          * Changelogs mask may change between open and close operations, but
3201          * this is not a big deal if we have a CL_CLOSE entry with no matching
3202          * CL_OPEN. Plus Changelogs mask may not change often.
3203          */
3204         if (((!(mdd->mdd_cl.mc_mask & (1 << CL_OPEN)) &&
3205               (mode & (MDS_FMODE_WRITE | MDS_OPEN_APPEND | MDS_OPEN_TRUNC))) ||
3206              ((mdd->mdd_cl.mc_mask & (1 << CL_OPEN)) && last_close_by_uid)) &&
3207             !(ma->ma_valid & MA_FLAGS && ma->ma_attr_flags & MDS_RECOV_OPEN)) {
3208                 if (handle == NULL) {
3209                         handle = mdd_trans_create(env, mdo2mdd(obj));
3210                         if (IS_ERR(handle))
3211                                 GOTO(stop, rc = PTR_ERR(handle));
3212
3213                         rc = mdd_declare_changelog_store(env, mdd, CL_CLOSE,
3214                                                          NULL, NULL, handle);
3215                         if (rc)
3216                                 GOTO(stop, rc);
3217
3218                         rc = mdd_trans_start(env, mdo2mdd(obj), handle);
3219                         if (rc)
3220                                 GOTO(stop, rc);
3221                 }
3222
3223                 mdd_changelog_data_store(env, mdd, CL_CLOSE, mode,
3224                                          mdd_obj, handle);
3225         }
3226
3227 stop:
3228         if (handle != NULL && !IS_ERR(handle))
3229                 rc = mdd_trans_stop(env, mdd, rc, handle);
3230
3231         return rc;
3232 }
3233
3234 /*
3235  * Permission check is done when open,
3236  * no need check again.
3237  */
3238 static int mdd_readpage_sanity_check(const struct lu_env *env,
3239                                      struct mdd_object *obj)
3240 {
3241         struct dt_object *next = mdd_object_child(obj);
3242         int rc;
3243         ENTRY;
3244
3245         if (S_ISDIR(mdd_object_type(obj)) && dt_try_as_dir(env, next))
3246                 rc = 0;
3247         else
3248                 rc = -ENOTDIR;
3249
3250         RETURN(rc);
3251 }
3252
3253 static int mdd_dir_page_build(const struct lu_env *env, union lu_page *lp,
3254                               size_t nob, const struct dt_it_ops *iops,
3255                               struct dt_it *it, __u32 attr, void *arg)
3256 {
3257         struct lu_dirpage       *dp = &lp->lp_dir;
3258         void                    *area = dp;
3259         int                      result;
3260         __u64                    hash = 0;
3261         struct lu_dirent        *ent;
3262         struct lu_dirent        *last = NULL;
3263         struct lu_fid            fid;
3264         int                      first = 1;
3265
3266         if (nob < sizeof(*dp))
3267                 return -EINVAL;
3268
3269         memset(area, 0, sizeof (*dp));
3270         area += sizeof (*dp);
3271         nob  -= sizeof (*dp);
3272
3273         ent  = area;
3274         do {
3275                 int    len;
3276                 size_t recsize;
3277
3278                 len = iops->key_size(env, it);
3279
3280                 /* IAM iterator can return record with zero len. */
3281                 if (len == 0)
3282                         goto next;
3283
3284                 hash = iops->store(env, it);
3285                 if (unlikely(first)) {
3286                         first = 0;
3287                         dp->ldp_hash_start = cpu_to_le64(hash);
3288                 }
3289
3290                 /* calculate max space required for lu_dirent */
3291                 recsize = lu_dirent_calc_size(len, attr);
3292
3293                 if (nob >= recsize) {
3294                         result = iops->rec(env, it, (struct dt_rec *)ent, attr);
3295                         if (result == -ESTALE)
3296                                 goto next;
3297                         if (result != 0)
3298                                 goto out;
3299
3300                         /* osd might not able to pack all attributes,
3301                          * so recheck rec length */
3302                         recsize = le16_to_cpu(ent->lde_reclen);
3303
3304                         if (le32_to_cpu(ent->lde_attrs) & LUDA_FID) {
3305                                 fid_le_to_cpu(&fid, &ent->lde_fid);
3306                                 if (fid_is_dot_lustre(&fid))
3307                                         goto next;
3308                         }
3309                 } else {
3310                         result = (last != NULL) ? 0 :-EINVAL;
3311                         goto out;
3312                 }
3313                 last = ent;
3314                 ent = (void *)ent + recsize;
3315                 nob -= recsize;
3316
3317 next:
3318                 result = iops->next(env, it);
3319                 if (result == -ESTALE)
3320                         goto next;
3321         } while (result == 0);
3322
3323 out:
3324         dp->ldp_hash_end = cpu_to_le64(hash);
3325         if (last != NULL) {
3326                 if (last->lde_hash == dp->ldp_hash_end)
3327                         dp->ldp_flags |= cpu_to_le32(LDF_COLLIDE);
3328                 last->lde_reclen = 0; /* end mark */
3329         }
3330         if (result > 0)
3331                 /* end of directory */
3332                 dp->ldp_hash_end = cpu_to_le64(MDS_DIR_END_OFF);
3333         else if (result < 0)
3334                 CWARN("build page failed: %d!\n", result);
3335         return result;
3336 }
3337
3338 int mdd_readpage(const struct lu_env *env, struct md_object *obj,
3339                  const struct lu_rdpg *rdpg)
3340 {
3341         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3342         int rc;
3343         ENTRY;
3344
3345         if (mdd_object_exists(mdd_obj) == 0) {
3346                 CERROR("%s: object "DFID" not found: rc = -2\n",
3347                        mdd_obj_dev_name(mdd_obj),PFID(mdd_object_fid(mdd_obj)));
3348                 return -ENOENT;
3349         }
3350
3351         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
3352         rc = mdd_readpage_sanity_check(env, mdd_obj);
3353         if (rc)
3354                 GOTO(out_unlock, rc);
3355
3356         if (mdd_is_dead_obj(mdd_obj)) {
3357                 struct page *pg;
3358                 struct lu_dirpage *dp;
3359
3360                 /*
3361                  * According to POSIX, please do not return any entry to client:
3362                  * even dot and dotdot should not be returned.
3363                  */
3364                 CDEBUG(D_INODE, "readdir from dead object: "DFID"\n",
3365                        PFID(mdd_object_fid(mdd_obj)));
3366
3367                 if (rdpg->rp_count <= 0)
3368                         GOTO(out_unlock, rc = -EFAULT);
3369                 LASSERT(rdpg->rp_pages != NULL);
3370
3371                 pg = rdpg->rp_pages[0];
3372                 dp = (struct lu_dirpage *)kmap(pg);
3373                 memset(dp, 0 , sizeof(struct lu_dirpage));
3374                 dp->ldp_hash_start = cpu_to_le64(rdpg->rp_hash);
3375                 dp->ldp_hash_end   = cpu_to_le64(MDS_DIR_END_OFF);
3376                 dp->ldp_flags = cpu_to_le32(LDF_EMPTY);
3377                 kunmap(pg);
3378                 GOTO(out_unlock, rc = LU_PAGE_SIZE);
3379         }
3380
3381         rc = dt_index_walk(env, mdd_object_child(mdd_obj), rdpg,
3382                            mdd_dir_page_build, NULL);
3383         if (rc >= 0) {
3384                 struct lu_dirpage       *dp;
3385
3386                 dp = kmap(rdpg->rp_pages[0]);
3387                 dp->ldp_hash_start = cpu_to_le64(rdpg->rp_hash);
3388                 if (rc == 0) {
3389                         /*
3390                          * No pages were processed, mark this for first page
3391                          * and send back.
3392                          */
3393                         dp->ldp_hash_end = cpu_to_le64(MDS_DIR_END_OFF);
3394                         dp->ldp_flags = cpu_to_le32(LDF_EMPTY);
3395                         rc = min_t(unsigned int, LU_PAGE_SIZE, rdpg->rp_count);
3396                 }
3397                 kunmap(rdpg->rp_pages[0]);
3398         }
3399
3400         GOTO(out_unlock, rc);
3401 out_unlock:
3402         mdd_read_unlock(env, mdd_obj);
3403         return rc;
3404 }
3405
3406 static int mdd_object_sync(const struct lu_env *env, struct md_object *obj)
3407 {
3408         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3409
3410         if (mdd_object_exists(mdd_obj) == 0) {
3411                 int rc = -ENOENT;
3412
3413                 CERROR("%s: object "DFID" not found: rc = %d\n",
3414                        mdd_obj_dev_name(mdd_obj),
3415                        PFID(mdd_object_fid(mdd_obj)), rc);
3416                 return rc;
3417         }
3418         return dt_object_sync(env, mdd_object_child(mdd_obj),
3419                               0, OBD_OBJECT_EOF);
3420 }
3421
3422 static int mdd_object_lock(const struct lu_env *env,
3423                            struct md_object *obj,
3424                            struct lustre_handle *lh,
3425                            struct ldlm_enqueue_info *einfo,
3426                            union ldlm_policy_data *policy)
3427 {
3428         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3429         return dt_object_lock(env, mdd_object_child(mdd_obj), lh,
3430                               einfo, policy);
3431 }
3432
3433 static int mdd_object_unlock(const struct lu_env *env,
3434                              struct md_object *obj,
3435                              struct ldlm_enqueue_info *einfo,
3436                              union ldlm_policy_data *policy)
3437 {
3438         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3439         return dt_object_unlock(env, mdd_object_child(mdd_obj), einfo, policy);
3440 }
3441
3442 const struct md_object_operations mdd_obj_ops = {
3443         .moo_permission         = mdd_permission,
3444         .moo_attr_get           = mdd_attr_get,
3445         .moo_attr_set           = mdd_attr_set,
3446         .moo_xattr_get          = mdd_xattr_get,
3447         .moo_xattr_set          = mdd_xattr_set,
3448         .moo_xattr_list         = mdd_xattr_list,
3449         .moo_invalidate         = mdd_invalidate,
3450         .moo_xattr_del          = mdd_xattr_del,
3451         .moo_swap_layouts       = mdd_swap_layouts,
3452         .moo_open               = mdd_open,
3453         .moo_close              = mdd_close,
3454         .moo_readpage           = mdd_readpage,
3455         .moo_readlink           = mdd_readlink,
3456         .moo_changelog          = mdd_changelog,
3457         .moo_object_sync        = mdd_object_sync,
3458         .moo_object_lock        = mdd_object_lock,
3459         .moo_object_unlock      = mdd_object_unlock,
3460         .moo_layout_change      = mdd_layout_change,
3461 };