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