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