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