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