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