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