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