Whamcloud - gitweb
LU-15171 osd-ldiskfs: xattr_sem locking is missing for dquot_transfer
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_handler.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/osd/osd_handler.c
32  *
33  * Top-level entry points into osd module
34  *
35  * Author: Nikita Danilov <nikita@clusterfs.com>
36  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
37  */
38
39 #define DEBUG_SUBSYSTEM S_OSD
40
41 #include <linux/fs_struct.h>
42 #include <linux/kallsyms.h>
43 #include <linux/module.h>
44 #include <linux/user_namespace.h>
45 #include <linux/uidgid.h>
46
47 /* prerequisite for linux/xattr.h */
48 #include <linux/types.h>
49 /* prerequisite for linux/xattr.h */
50 #include <linux/fs.h>
51 /* XATTR_{REPLACE,CREATE} */
52 #include <linux/xattr.h>
53
54 #include <ldiskfs/ldiskfs.h>
55 #include <ldiskfs/xattr.h>
56 #include <ldiskfs/ldiskfs_extents.h>
57 #undef ENTRY
58 /*
59  * struct OBD_{ALLOC,FREE}*()
60  * OBD_FAIL_CHECK
61  */
62 #include <obd_support.h>
63 /* struct ptlrpc_thread */
64 #include <lustre_net.h>
65 #include <lustre_fid.h>
66 /* process_config */
67 #include <uapi/linux/lustre/lustre_param.h>
68
69 #include "osd_internal.h"
70 #include "osd_dynlocks.h"
71
72 /* llo_* api support */
73 #include <md_object.h>
74 #include <lustre_quota.h>
75
76 #include <lustre_linkea.h>
77
78 /* encoding routines */
79 #include <lustre_crypto.h>
80
81 /* Maximum EA size is limited by LNET_MTU for remote objects */
82 #define OSD_MAX_EA_SIZE 1048364
83
84 int ldiskfs_pdo = 1;
85 module_param(ldiskfs_pdo, int, 0644);
86 MODULE_PARM_DESC(ldiskfs_pdo, "ldiskfs with parallel directory operations");
87
88 int ldiskfs_track_declares_assert;
89 module_param(ldiskfs_track_declares_assert, int, 0644);
90 MODULE_PARM_DESC(ldiskfs_track_declares_assert, "LBUG during tracking of declares");
91
92 /* Slab to allocate dynlocks */
93 struct kmem_cache *dynlock_cachep;
94
95 /* Slab to allocate osd_it_ea */
96 struct kmem_cache *osd_itea_cachep;
97
98 static struct lu_kmem_descr ldiskfs_caches[] = {
99         {
100                 .ckd_cache = &dynlock_cachep,
101                 .ckd_name  = "dynlock_cache",
102                 .ckd_size  = sizeof(struct dynlock_handle)
103         },
104         {
105                 .ckd_cache = &osd_itea_cachep,
106                 .ckd_name  = "osd_itea_cache",
107                 .ckd_size  = sizeof(struct osd_it_ea)
108         },
109         {
110                 .ckd_cache = NULL
111         }
112 };
113
114 static const char dot[] = ".";
115 static const char dotdot[] = "..";
116
117 static const struct lu_object_operations      osd_lu_obj_ops;
118 static const struct dt_object_operations      osd_obj_ops;
119 static const struct dt_object_operations      osd_obj_otable_it_ops;
120 static const struct dt_index_operations       osd_index_iam_ops;
121 static const struct dt_index_operations       osd_index_ea_ops;
122
123 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
124                           const struct lu_fid *fid);
125 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
126                                                 struct osd_device *osd);
127
128 int osd_trans_declare_op2rb[] = {
129         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
130         [OSD_OT_PUNCH]          = OSD_OT_MAX,
131         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
132         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
133         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
134         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
135         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
136         [OSD_OT_WRITE]          = OSD_OT_WRITE,
137         [OSD_OT_INSERT]         = OSD_OT_DELETE,
138         [OSD_OT_DELETE]         = OSD_OT_INSERT,
139         [OSD_OT_QUOTA]          = OSD_OT_MAX,
140 };
141
142 static int osd_has_index(const struct osd_object *obj)
143 {
144         return obj->oo_dt.do_index_ops != NULL;
145 }
146
147 static int osd_object_invariant(const struct lu_object *l)
148 {
149         return osd_invariant(osd_obj(l));
150 }
151
152 /*
153  * Concurrency: doesn't matter
154  */
155 static int osd_is_write_locked(const struct lu_env *env, struct osd_object *o)
156 {
157         struct osd_thread_info *oti = osd_oti_get(env);
158
159         return oti->oti_w_locks > 0 && o->oo_owner == env;
160 }
161
162 /*
163  * Concurrency: doesn't access mutable data
164  */
165 static int osd_root_get(const struct lu_env *env,
166                         struct dt_device *dev, struct lu_fid *f)
167 {
168         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
169         return 0;
170 }
171
172 /*
173  * the following set of functions are used to maintain per-thread
174  * cache of FID->ino mapping. this mechanism is needed to resolve
175  * FID to inode at dt_insert() which in turn stores ino in the
176  * directory entries to keep ldiskfs compatible with ext[34].
177  * due to locking-originated restrictions we can't lookup ino
178  * using LU cache (deadlock is possible). lookup using OI is quite
179  * expensive. so instead we maintain this cache and methods like
180  * dt_create() fill it. so in the majority of cases dt_insert() is
181  * able to find needed mapping in lockless manner.
182  */
183 static struct osd_idmap_cache *
184 osd_idc_find(const struct lu_env *env, struct osd_device *osd,
185              const struct lu_fid *fid)
186 {
187         struct osd_thread_info *oti = osd_oti_get(env);
188         struct osd_idmap_cache *idc = oti->oti_ins_cache;
189         int i;
190
191         for (i = 0; i < oti->oti_ins_cache_used; i++) {
192                 if (!lu_fid_eq(&idc[i].oic_fid, fid))
193                         continue;
194                 if (idc[i].oic_dev != osd)
195                         continue;
196
197                 return idc + i;
198         }
199
200         return NULL;
201 }
202
203 static struct osd_idmap_cache *
204 osd_idc_add(const struct lu_env *env, struct osd_device *osd,
205             const struct lu_fid *fid)
206 {
207         struct osd_thread_info *oti   = osd_oti_get(env);
208         struct osd_idmap_cache *idc;
209         int i;
210
211         if (unlikely(oti->oti_ins_cache_used >= oti->oti_ins_cache_size)) {
212                 i = oti->oti_ins_cache_size * 2;
213                 if (i == 0)
214                         i = OSD_INS_CACHE_SIZE;
215                 OBD_ALLOC_PTR_ARRAY(idc, i);
216                 if (idc == NULL)
217                         return ERR_PTR(-ENOMEM);
218                 if (oti->oti_ins_cache != NULL) {
219                         memcpy(idc, oti->oti_ins_cache,
220                                oti->oti_ins_cache_used * sizeof(*idc));
221                         OBD_FREE_PTR_ARRAY(oti->oti_ins_cache,
222                                            oti->oti_ins_cache_used);
223                 }
224                 oti->oti_ins_cache = idc;
225                 oti->oti_ins_cache_size = i;
226         }
227
228         idc = oti->oti_ins_cache + oti->oti_ins_cache_used++;
229         idc->oic_fid = *fid;
230         idc->oic_dev = osd;
231         idc->oic_lid.oii_ino = 0;
232         idc->oic_lid.oii_gen = 0;
233         idc->oic_remote = 0;
234
235         return idc;
236 }
237
238 /*
239  * lookup mapping for the given fid in the cache, initialize a
240  * new one if not found. the initialization checks whether the
241  * object is local or remote. for local objects, OI is used to
242  * learn ino/generation. the function is used when the caller
243  * has no information about the object, e.g. at dt_insert().
244  */
245 static struct osd_idmap_cache *
246 osd_idc_find_or_init(const struct lu_env *env, struct osd_device *osd,
247                      const struct lu_fid *fid)
248 {
249         struct osd_idmap_cache *idc;
250         int rc;
251
252         idc = osd_idc_find(env, osd, fid);
253         LASSERT(!IS_ERR(idc));
254         if (idc != NULL)
255                 return idc;
256
257         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
258                osd->od_svname, PFID(fid));
259
260         /* new mapping is needed */
261         idc = osd_idc_add(env, osd, fid);
262         if (IS_ERR(idc)) {
263                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
264                        osd->od_svname, PFID(fid), PTR_ERR(idc));
265                 return idc;
266         }
267
268         /* initialize it */
269         rc = osd_remote_fid(env, osd, fid);
270         if (unlikely(rc < 0))
271                 return ERR_PTR(rc);
272
273         if (rc == 0) {
274                 /* the object is local, lookup in OI */
275                 /* XXX: probably cheaper to lookup in LU first? */
276                 rc = osd_oi_lookup(osd_oti_get(env), osd, fid,
277                                    &idc->oic_lid, 0);
278                 if (unlikely(rc < 0)) {
279                         CERROR("can't lookup: rc = %d\n", rc);
280                         return ERR_PTR(rc);
281                 }
282         } else {
283                 /* the object is remote */
284                 idc->oic_remote = 1;
285         }
286
287         return idc;
288 }
289
290 static void osd_idc_dump_lma(const struct lu_env *env,
291                                 struct osd_device *osd,
292                                 unsigned long ino,
293                                 bool check_in_oi)
294 {
295         struct osd_thread_info *info = osd_oti_get(env);
296         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
297         const struct lu_fid *fid;
298         struct osd_inode_id lid;
299         struct inode *inode;
300         int rc;
301
302         inode = osd_ldiskfs_iget(osd_sb(osd), ino);
303         if (IS_ERR(inode)) {
304                 CERROR("%s: can't get inode %lu: rc = %d\n",
305                        osd->od_svname, ino, (int)PTR_ERR(inode));
306                 return;
307         }
308         if (is_bad_inode(inode)) {
309                 CERROR("%s: bad inode %lu\n", osd->od_svname, ino);
310                 goto put;
311         }
312         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
313         if (rc) {
314                 CERROR("%s: can't get LMA for %lu: rc = %d\n",
315                        osd->od_svname, ino, rc);
316                 goto put;
317         }
318         fid = &loa->loa_lma.lma_self_fid;
319         LCONSOLE(D_INFO, "%s: "DFID" in inode %lu/%u\n", osd->od_svname,
320                       PFID(fid), ino, (unsigned)inode->i_generation);
321         if (!check_in_oi)
322                 goto put;
323         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
324         if (rc) {
325                 CERROR("%s: can't lookup "DFID": rc = %d\n",
326                        osd->od_svname, PFID(fid), rc);
327                 goto put;
328         }
329         LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n", osd->od_svname,
330                       PFID(fid), lid.oii_ino, lid.oii_gen);
331 put:
332         iput(inode);
333 }
334
335 static void osd_idc_dump_debug(const struct lu_env *env,
336                                 struct osd_device *osd,
337                                 const struct lu_fid *fid,
338                                 unsigned long ino1,
339                                 unsigned long ino2)
340 {
341         struct osd_inode_id lid;
342
343         int rc;
344
345         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
346         if (!rc) {
347                 LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n",
348                         osd->od_svname, PFID(fid), lid.oii_ino, lid.oii_gen);
349                 osd_idc_dump_lma(env, osd, lid.oii_ino, false);
350         } else {
351                 CERROR("%s: can't lookup "DFID": rc = %d\n",
352                        osd->od_svname, PFID(fid), rc);
353         }
354         if (ino1)
355                 osd_idc_dump_lma(env, osd, ino1, true);
356         if (ino2)
357                 osd_idc_dump_lma(env, osd, ino2, true);
358 }
359
360 /*
361  * lookup mapping for given FID and fill it from the given object.
362  * the object is lolcal by definition.
363  */
364 static int osd_idc_find_and_init(const struct lu_env *env,
365                                  struct osd_device *osd,
366                                  struct osd_object *obj)
367 {
368         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
369         struct osd_idmap_cache *idc;
370
371         idc = osd_idc_find(env, osd, fid);
372         LASSERT(!IS_ERR(idc));
373         if (idc != NULL) {
374                 if (obj->oo_inode == NULL)
375                         return 0;
376                 if (idc->oic_lid.oii_ino != obj->oo_inode->i_ino) {
377                         if (idc->oic_lid.oii_ino) {
378                                 osd_idc_dump_debug(env, osd, fid,
379                                                    idc->oic_lid.oii_ino,
380                                                    obj->oo_inode->i_ino);
381                                 return -EINVAL;
382                         }
383                         idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
384                         idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
385                 }
386                 return 0;
387         }
388
389         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
390                osd->od_svname, PFID(fid));
391
392         /* new mapping is needed */
393         idc = osd_idc_add(env, osd, fid);
394         if (IS_ERR(idc)) {
395                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
396                        osd->od_svname, PFID(fid), PTR_ERR(idc));
397                 return PTR_ERR(idc);
398         }
399
400         if (obj->oo_inode != NULL) {
401                 idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
402                 idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
403         }
404         return 0;
405 }
406
407 /*
408  * OSD object methods.
409  */
410
411 /*
412  * Concurrency: no concurrent access is possible that early in object
413  * life-cycle.
414  */
415 static struct lu_object *osd_object_alloc(const struct lu_env *env,
416                                           const struct lu_object_header *hdr,
417                                           struct lu_device *d)
418 {
419         struct osd_object *mo;
420
421         OBD_ALLOC_PTR(mo);
422         if (mo != NULL) {
423                 struct lu_object *l;
424                 struct lu_object_header *h;
425                 struct osd_device *o = osd_dev(d);
426
427                 l = &mo->oo_dt.do_lu;
428                 if (unlikely(o->od_in_init)) {
429                         OBD_ALLOC_PTR(h);
430                         if (!h) {
431                                 OBD_FREE_PTR(mo);
432                                 return NULL;
433                         }
434
435                         lu_object_header_init(h);
436                         lu_object_init(l, h, d);
437                         lu_object_add_top(h, l);
438                         mo->oo_header = h;
439                 } else {
440                         dt_object_init(&mo->oo_dt, NULL, d);
441                         mo->oo_header = NULL;
442                 }
443
444                 mo->oo_dt.do_ops = &osd_obj_ops;
445                 l->lo_ops = &osd_lu_obj_ops;
446                 init_rwsem(&mo->oo_sem);
447                 init_rwsem(&mo->oo_ext_idx_sem);
448                 spin_lock_init(&mo->oo_guard);
449                 INIT_LIST_HEAD(&mo->oo_xattr_list);
450                 return l;
451         }
452         return NULL;
453 }
454
455 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
456                 struct dentry *dentry, struct lustre_ost_attrs *loa)
457 {
458         int rc;
459
460         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
461                              (void *)loa, sizeof(*loa));
462         if (rc > 0) {
463                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
464
465                 if (rc < sizeof(*lma))
466                         return -EINVAL;
467
468                 rc = 0;
469                 lustre_loa_swab(loa, true);
470                 /* Check LMA compatibility */
471                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
472                         rc = -EOPNOTSUPP;
473                         CWARN("%s: unsupported incompat LMA feature(s) %#x for fid = "DFID", ino = %lu: rc = %d\n",
474                               osd_ino2name(inode),
475                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
476                               PFID(&lma->lma_self_fid), inode->i_ino, rc);
477                 }
478         } else if (rc == 0) {
479                 rc = -ENODATA;
480         }
481
482         return rc;
483 }
484
485 /*
486  * retrieve object from backend ext fs.
487  **/
488 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
489                        struct osd_inode_id *id)
490 {
491         int rc;
492         struct inode *inode = NULL;
493
494         /*
495          * if we look for an inode withing a running
496          * transaction, then we risk to deadlock
497          * osd_dirent_check_repair() breaks this
498          */
499          /* LASSERT(current->journal_info == NULL); */
500
501         inode = osd_ldiskfs_iget(osd_sb(dev), id->oii_ino);
502         if (IS_ERR(inode)) {
503                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
504                        id->oii_ino, PTR_ERR(inode));
505         } else if (id->oii_gen != OSD_OII_NOGEN &&
506                    inode->i_generation != id->oii_gen) {
507                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
508                        "i_generation = %u\n",
509                        id->oii_ino, id->oii_gen, inode->i_generation);
510                 iput(inode);
511                 inode = ERR_PTR(-ESTALE);
512         } else if (inode->i_nlink == 0) {
513                 /*
514                  * due to parallel readdir and unlink,
515                  * we can have dead inode here.
516                  */
517                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
518                 iput(inode);
519                 inode = ERR_PTR(-ESTALE);
520         } else if (is_bad_inode(inode)) {
521                 rc = -ENOENT;
522                 CWARN("%s: bad inode: ino = %u: rc = %d\n",
523                       osd_dev2name(dev), id->oii_ino, rc);
524                 iput(inode);
525                 inode = ERR_PTR(rc);
526         } else if ((rc = osd_attach_jinode(inode))) {
527                 iput(inode);
528                 inode = ERR_PTR(rc);
529         } else {
530                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
531                 if (id->oii_gen == OSD_OII_NOGEN)
532                         osd_id_gen(id, inode->i_ino, inode->i_generation);
533
534                 /*
535                  * Do not update file c/mtime in ldiskfs.
536                  * NB: we don't have any lock to protect this because we don't
537                  * have reference on osd_object now, but contention with
538                  * another lookup + attr_set can't happen in the tiny window
539                  * between if (...) and set S_NOCMTIME.
540                  */
541                 if (!(inode->i_flags & S_NOCMTIME))
542                         inode->i_flags |= S_NOCMTIME;
543         }
544         return inode;
545 }
546
547 int osd_ldiskfs_add_entry(struct osd_thread_info *info, struct osd_device *osd,
548                           handle_t *handle, struct dentry *child,
549                           struct inode *inode, struct htree_lock *hlock)
550 {
551         int rc, rc2;
552
553         rc = __ldiskfs_add_entry(handle, child, inode, hlock);
554         if (rc == -ENOBUFS || rc == -ENOSPC) {
555                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
556                 struct inode *parent = child->d_parent->d_inode;
557                 struct lu_fid *fid = NULL;
558                 char fidstr[FID_LEN + 1] = "unknown";
559
560                 rc2 = osd_get_lma(info, parent, child->d_parent, loa);
561                 if (!rc2) {
562                         fid = &loa->loa_lma.lma_self_fid;
563                 } else if (rc2 == -ENODATA) {
564                         if (unlikely(is_root_inode(parent))) {
565                                 fid = &info->oti_fid3;
566                                 lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
567                         } else if (!osd->od_is_ost && osd->od_index == 0) {
568                                 fid = &info->oti_fid3;
569                                 lu_igif_build(fid, parent->i_ino,
570                                               parent->i_generation);
571                         }
572                 }
573
574                 if (fid != NULL)
575                         snprintf(fidstr, sizeof(fidstr), DFID, PFID(fid));
576
577                 /* below message is checked in sanity.sh test_129 */
578                 if (rc == -ENOSPC) {
579                         CWARN("%s: directory (inode: %lu, FID: %s) has reached max size limit\n",
580                               osd_name(osd), parent->i_ino, fidstr);
581                 } else {
582                         rc = 0; /* ignore such error now */
583                         CWARN("%s: directory (inode: %lu, FID: %s) is approaching max size limit\n",
584                               osd_name(osd), parent->i_ino, fidstr);
585                 }
586
587         }
588
589         return rc;
590 }
591
592
593 struct inode *
594 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
595              struct osd_inode_id *id, struct lu_fid *fid)
596 {
597         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
598         struct inode *inode;
599         int rc;
600
601         inode = osd_iget(info, dev, id);
602         if (IS_ERR(inode))
603                 return inode;
604
605         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
606         if (!rc) {
607                 *fid = loa->loa_lma.lma_self_fid;
608         } else if (rc == -ENODATA) {
609                 if (unlikely(is_root_inode(inode)))
610                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
611                 else
612                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
613         } else {
614                 iput(inode);
615                 inode = ERR_PTR(rc);
616         }
617         return inode;
618 }
619
620 static struct inode *osd_iget_check(struct osd_thread_info *info,
621                                     struct osd_device *dev,
622                                     const struct lu_fid *fid,
623                                     struct osd_inode_id *id,
624                                     bool trusted)
625 {
626         struct inode *inode;
627         int rc = 0;
628
629         ENTRY;
630
631         /*
632          * The cached OI mapping is trustable. If we cannot locate the inode
633          * via the cached OI mapping, then return the failure to the caller
634          * directly without further OI checking.
635          */
636
637 again:
638         inode = osd_ldiskfs_iget(osd_sb(dev), id->oii_ino);
639         if (IS_ERR(inode)) {
640                 rc = PTR_ERR(inode);
641                 if (!trusted && (rc == -ENOENT || rc == -ESTALE))
642                         goto check_oi;
643
644                 CDEBUG(D_INODE, "no inode for FID: "DFID", ino = %u, rc = %d\n",
645                        PFID(fid), id->oii_ino, rc);
646                 GOTO(put, rc);
647         }
648
649         if (is_bad_inode(inode)) {
650                 rc = -ENOENT;
651                 if (!trusted)
652                         goto check_oi;
653
654                 CDEBUG(D_INODE, "bad inode for FID: "DFID", ino = %u\n",
655                        PFID(fid), id->oii_ino);
656                 GOTO(put, rc);
657         }
658
659         if (id->oii_gen != OSD_OII_NOGEN &&
660             inode->i_generation != id->oii_gen) {
661                 rc = -ESTALE;
662                 if (!trusted)
663                         goto check_oi;
664
665                 CDEBUG(D_INODE, "unmatched inode for FID: "DFID", ino = %u, "
666                        "oii_gen = %u, i_generation = %u\n", PFID(fid),
667                        id->oii_ino, id->oii_gen, inode->i_generation);
668                 GOTO(put, rc);
669         }
670
671         if (inode->i_nlink == 0) {
672                 rc = -ENOENT;
673                 if (!trusted)
674                         goto check_oi;
675
676                 CDEBUG(D_INODE, "stale inode for FID: "DFID", ino = %u\n",
677                        PFID(fid), id->oii_ino);
678                 GOTO(put, rc);
679         }
680
681         ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
682
683 check_oi:
684         if (rc != 0) {
685                 __u32 saved_ino = id->oii_ino;
686                 __u32 saved_gen = id->oii_gen;
687
688                 LASSERT(!trusted);
689                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
690
691                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
692                 /*
693                  * XXX: There are four possible cases:
694                  *      1. rc = 0.
695                  *         Backup/restore caused the OI invalid.
696                  *      2. rc = 0.
697                  *         Someone unlinked the object but NOT removed
698                  *         the OI mapping, such as mount target device
699                  *         as ldiskfs, and modify something directly.
700                  *      3. rc = -ENOENT.
701                  *         Someone just removed the object between the
702                  *         former oi_lookup and the iget. It is normal.
703                  *      4. Other failure cases.
704                  *
705                  *      Generally, when the device is mounted, it will
706                  *      auto check whether the system is restored from
707                  *      file-level backup or not. We trust such detect
708                  *      to distinguish the 1st case from the 2nd case:
709                  *      if the OI files are consistent but may contain
710                  *      stale OI mappings because of case 2, if iget()
711                  *      returns -ENOENT or -ESTALE, then it should be
712                  *      the case 2.
713                  */
714                 if (rc != 0)
715                         /*
716                          * If the OI mapping was in OI file before the
717                          * osd_iget_check(), but now, it is disappear,
718                          * then it must be removed by race. That is a
719                          * normal race case.
720                          */
721                         GOTO(put, rc);
722
723                 /*
724                  * It is the OI scrub updated the OI mapping by race.
725                  * The new OI mapping must be valid.
726                  */
727                 if (saved_ino != id->oii_ino ||
728                     (saved_gen != id->oii_gen && saved_gen != OSD_OII_NOGEN)) {
729                         if (!IS_ERR(inode))
730                                 iput(inode);
731
732                         trusted = true;
733                         goto again;
734                 }
735
736                 if (IS_ERR(inode)) {
737                         if (dev->od_scrub.os_scrub.os_file.sf_flags &
738                             SF_INCONSISTENT)
739                                 /*
740                                  * It still can be the case 2, but we cannot
741                                  * distinguish it from the case 1. So return
742                                  * -EREMCHG to block current operation until
743                                  *  OI scrub rebuilt the OI mappings.
744                                  */
745                                 rc = -EREMCHG;
746                         else
747                                 rc = -ENOENT;
748
749                         GOTO(put, rc);
750                 }
751
752                 if (inode->i_generation == id->oii_gen)
753                         rc = -ENOENT;
754                 else
755                         rc = -EREMCHG;
756         } else {
757                 if (id->oii_gen == OSD_OII_NOGEN)
758                         osd_id_gen(id, inode->i_ino, inode->i_generation);
759
760                 /*
761                  * Do not update file c/mtime in ldiskfs.
762                  * NB: we don't have any lock to protect this because we don't
763                  * have reference on osd_object now, but contention with
764                  * another lookup + attr_set can't happen in the tiny window
765                  * between if (...) and set S_NOCMTIME.
766                  */
767                 if (!(inode->i_flags & S_NOCMTIME))
768                         inode->i_flags |= S_NOCMTIME;
769         }
770
771         GOTO(put, rc);
772
773 put:
774         if (rc != 0) {
775                 if (!IS_ERR(inode))
776                         iput(inode);
777
778                 inode = ERR_PTR(rc);
779         }
780
781         return inode;
782 }
783
784 /**
785  * \retval +v: new filter_fid does not contain self-fid
786  * \retval 0:  filter_fid_18_23, contains self-fid
787  * \retval -v: other failure cases
788  */
789 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
790                  struct dentry *dentry, struct lu_fid *fid)
791 {
792         struct filter_fid *ff = &info->oti_ff;
793         struct ost_id *ostid = &info->oti_ostid;
794         int rc;
795
796         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
797         if (rc == sizeof(struct filter_fid_18_23)) {
798                 struct filter_fid_18_23 *ff_old = (void *)ff;
799
800                 ostid_set_seq(ostid, le64_to_cpu(ff_old->ff_seq));
801                 rc = ostid_set_id(ostid, le64_to_cpu(ff_old->ff_objid));
802                 /*
803                  * XXX: use 0 as the index for compatibility, the caller will
804                  * handle index related issues when necessary.
805                  */
806                 if (!rc)
807                         ostid_to_fid(fid, ostid, 0);
808         } else if (rc >= (int)sizeof(struct filter_fid_24_29)) {
809                 rc = 1;
810         } else if (rc >= 0) {
811                 rc = -EINVAL;
812         }
813
814         return rc;
815 }
816
817 static int osd_lma_self_repair(struct osd_thread_info *info,
818                                struct osd_device *osd, struct inode *inode,
819                                const struct lu_fid *fid, __u32 compat)
820 {
821         handle_t *jh;
822         int rc;
823
824         LASSERT(current->journal_info == NULL);
825
826         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
827                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
828         if (IS_ERR(jh)) {
829                 rc = PTR_ERR(jh);
830                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
831                       osd_name(osd), rc);
832                 return rc;
833         }
834
835         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
836         if (rc != 0)
837                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
838                       osd_name(osd), rc);
839         ldiskfs_journal_stop(jh);
840         return rc;
841 }
842
843 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
844 {
845         struct osd_thread_info *info = osd_oti_get(env);
846         struct osd_device *osd = osd_obj2dev(obj);
847         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
848         struct lustre_mdt_attrs *lma = &loa->loa_lma;
849         struct inode *inode = obj->oo_inode;
850         struct dentry *dentry = &info->oti_obj_dentry;
851         struct lu_fid *fid = NULL;
852         const struct lu_fid *rfid = lu_object_fid(&obj->oo_dt.do_lu);
853         int rc;
854
855         ENTRY;
856
857         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
858                              (void *)loa, sizeof(*loa));
859         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
860                 fid = &lma->lma_self_fid;
861                 rc = osd_get_idif(info, inode, dentry, fid);
862                 if (rc > 0 || (rc == -ENODATA && osd->od_index_in_idif)) {
863                         /*
864                          * For the given OST-object, if it has neither LMA nor
865                          * FID in XATTR_NAME_FID, then the given FID (which is
866                          * contained in the @obj, from client RPC for locating
867                          * the OST-object) is trusted. We use it to generate
868                          * the LMA.
869                          */
870                         osd_lma_self_repair(info, osd, inode, rfid,
871                                             LMAC_FID_ON_OST);
872                         RETURN(0);
873                 }
874         }
875
876         if (rc < 0)
877                 RETURN(rc);
878
879         if (rc > 0) {
880                 rc = 0;
881                 lustre_lma_swab(lma);
882                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
883                              (CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT) &&
884                               S_ISREG(inode->i_mode)))) {
885                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
886                               "fid = "DFID", ino = %lu\n", osd_name(osd),
887                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
888                               PFID(rfid), inode->i_ino);
889                         rc = -EOPNOTSUPP;
890                 } else {
891                         fid = &lma->lma_self_fid;
892                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
893                             osd->od_is_ost)
894                                 obj->oo_pfid_in_lma = 1;
895                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
896                             !osd->od_is_ost)
897                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
898                 }
899         }
900
901         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
902                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
903                         struct ost_id   *oi   = &info->oti_ostid;
904                         struct lu_fid   *fid1 = &info->oti_fid3;
905                         __u32            idx  = fid_idif_ost_idx(rfid);
906
907                         /*
908                          * For old IDIF, the OST index is not part of the IDIF,
909                          * Means that different OSTs may have the same IDIFs.
910                          * Under such case, we need to make some compatible
911                          * check to make sure to trigger OI scrub properly.
912                          */
913                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
914                                 /* Given @rfid is new, LMA is old. */
915                                 fid_to_ostid(fid, oi);
916                                 ostid_to_fid(fid1, oi, idx);
917                                 if (lu_fid_eq(fid1, rfid)) {
918                                         if (osd->od_index_in_idif)
919                                                 osd_lma_self_repair(info, osd,
920                                                         inode, rfid,
921                                                         LMAC_FID_ON_OST);
922                                         RETURN(0);
923                                 }
924                         }
925                 }
926
927                 rc = -EREMCHG;
928         }
929
930         RETURN(rc);
931 }
932
933 struct osd_check_lmv_buf {
934         /* please keep it as first member */
935         struct dir_context ctx;
936         struct osd_thread_info *oclb_info;
937         struct osd_device *oclb_dev;
938         int oclb_items;
939         bool oclb_found;
940 };
941
942 /**
943  * It is called internally by ->iterate*() to filter out the
944  * local slave object's FID of the striped directory.
945  *
946  * \retval      1 found the local slave's FID
947  * \retval      0 continue to check next item
948  * \retval      -ve for failure
949  */
950 #ifdef HAVE_FILLDIR_USE_CTX
951 static int osd_stripe_dir_filldir(struct dir_context *buf,
952 #else
953 static int osd_stripe_dir_filldir(void *buf,
954 #endif
955                                   const char *name, int namelen,
956                                   loff_t offset, __u64 ino, unsigned int d_type)
957 {
958         struct osd_check_lmv_buf *oclb = (struct osd_check_lmv_buf *)buf;
959         struct osd_thread_info *oti = oclb->oclb_info;
960         struct lu_fid *fid = &oti->oti_fid3;
961         struct osd_inode_id *id = &oti->oti_id3;
962         struct osd_device *dev = oclb->oclb_dev;
963         struct inode *inode;
964
965         oclb->oclb_items++;
966
967         if (name[0] == '.')
968                 return 0;
969
970         fid_zero(fid);
971         sscanf(name + 1, SFID, RFID(fid));
972         if (!fid_is_sane(fid))
973                 return 0;
974
975         if (osd_remote_fid(oti->oti_env, dev, fid))
976                 return 0;
977
978         osd_id_gen(id, ino, OSD_OII_NOGEN);
979         inode = osd_iget(oti, dev, id);
980         if (IS_ERR(inode))
981                 return PTR_ERR(inode);
982
983         iput(inode);
984         osd_add_oi_cache(oti, dev, id, fid);
985         osd_oii_insert(dev, fid, id, true);
986         oclb->oclb_found = true;
987
988         return 1;
989 }
990
991 /*
992  * When lookup item under striped directory, we need to locate the master
993  * MDT-object of the striped directory firstly, then the client will send
994  * lookup (getattr_by_name) RPC to the MDT with some slave MDT-object's FID
995  * and the item's name. If the system is restored from MDT file level backup,
996  * then before the OI scrub completely built the OI files, the OI mappings of
997  * the master MDT-object and slave MDT-object may be invalid. Usually, it is
998  * not a problem for the master MDT-object. Because when locate the master
999  * MDT-object, we will do name based lookup (for the striped directory itself)
1000  * firstly, during such process we can setup the correct OI mapping for the
1001  * master MDT-object. But it will be trouble for the slave MDT-object. Because
1002  * the client will not trigger name based lookup on the MDT to locate the slave
1003  * MDT-object before locating item under the striped directory, then when
1004  * osd_fid_lookup(), it will find that the OI mapping for the slave MDT-object
1005  * is invalid and does not know what the right OI mapping is, then the MDT has
1006  * to return -EINPROGRESS to the client to notify that the OI scrub is rebuiding
1007  * the OI file, related OI mapping is unknown yet, please try again later. And
1008  * then client will re-try the RPC again and again until related OI mapping has
1009  * been updated. That is quite inefficient.
1010  *
1011  * To resolve above trouble, we will handle it as the following two cases:
1012  *
1013  * 1) The slave MDT-object and the master MDT-object are on different MDTs.
1014  *    It is relative easy. Be as one of remote MDT-objects, the slave MDT-object
1015  *    is linked under /REMOTE_PARENT_DIR with the name of its FID string.
1016  *    We can locate the slave MDT-object via lookup the /REMOTE_PARENT_DIR
1017  *    directly. Please check osd_fid_lookup().
1018  *
1019  * 2) The slave MDT-object and the master MDT-object reside on the same MDT.
1020  *    Under such case, during lookup the master MDT-object, we will lookup the
1021  *    slave MDT-object via readdir against the master MDT-object, because the
1022  *    slave MDT-objects information are stored as sub-directories with the name
1023  *    "${FID}:${index}". Then when find the local slave MDT-object, its OI
1024  *    mapping will be recorded. Then subsequent osd_fid_lookup() will know
1025  *    the correct OI mapping for the slave MDT-object.
1026  */
1027 static int osd_check_lmv(struct osd_thread_info *oti, struct osd_device *dev,
1028                          struct inode *inode)
1029 {
1030         struct lu_buf *buf = &oti->oti_big_buf;
1031         struct dentry *dentry = &oti->oti_obj_dentry;
1032         struct file *filp;
1033         struct lmv_mds_md_v1 *lmv1;
1034         struct osd_check_lmv_buf oclb = {
1035                 .ctx.actor = osd_stripe_dir_filldir,
1036                 .oclb_info = oti,
1037                 .oclb_dev = dev,
1038                 .oclb_found = false,
1039         };
1040         int rc = 0;
1041
1042         ENTRY;
1043
1044 again:
1045         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMV, buf->lb_buf,
1046                              buf->lb_len);
1047         if (rc == -ERANGE) {
1048                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMV, NULL, 0);
1049                 if (rc > 0) {
1050                         lu_buf_realloc(buf, rc);
1051                         if (buf->lb_buf == NULL)
1052                                 GOTO(out, rc = -ENOMEM);
1053
1054                         goto again;
1055                 }
1056         }
1057
1058         if (unlikely(rc == 0 || rc == -ENODATA))
1059                 GOTO(out, rc = 0);
1060
1061         if (rc < 0)
1062                 GOTO(out, rc);
1063
1064         if (unlikely(buf->lb_buf == NULL)) {
1065                 lu_buf_realloc(buf, rc);
1066                 if (buf->lb_buf == NULL)
1067                         GOTO(out, rc = -ENOMEM);
1068
1069                 goto again;
1070         }
1071
1072         lmv1 = buf->lb_buf;
1073         if (le32_to_cpu(lmv1->lmv_magic) != LMV_MAGIC_V1)
1074                 GOTO(out, rc = 0);
1075
1076         filp = osd_quasi_file(oti->oti_env, inode);
1077         rc = osd_security_file_alloc(filp);
1078         if (rc)
1079                 goto out;
1080
1081         do {
1082                 oclb.oclb_items = 0;
1083                 rc = iterate_dir(filp, &oclb.ctx);
1084         } while (rc >= 0 && oclb.oclb_items > 0 && !oclb.oclb_found &&
1085                  filp->f_pos != LDISKFS_HTREE_EOF_64BIT);
1086         inode->i_fop->release(inode, filp);
1087
1088 out:
1089         if (rc < 0)
1090                 CDEBUG(D_LFSCK,
1091                        "%s: cannot check LMV, ino = %lu/%u: rc = %d\n",
1092                        osd_ino2name(inode), inode->i_ino, inode->i_generation,
1093                        rc);
1094         else
1095                 rc = 0;
1096
1097         RETURN(rc);
1098 }
1099
1100 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
1101                           const struct lu_fid *fid,
1102                           const struct lu_object_conf *conf)
1103 {
1104         struct osd_thread_info *info;
1105         struct lu_device *ldev = obj->oo_dt.do_lu.lo_dev;
1106         struct osd_device *dev;
1107         struct osd_idmap_cache *oic;
1108         struct osd_inode_id *id;
1109         struct inode *inode = NULL;
1110         struct lustre_scrub *scrub;
1111         struct scrub_file *sf;
1112         __u32 flags = SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT | SS_AUTO_FULL;
1113         __u32 saved_ino;
1114         __u32 saved_gen;
1115         int result = 0;
1116         int rc1 = 0;
1117         bool remote = false;
1118         bool trusted = true;
1119         bool updated = false;
1120         bool checked = false;
1121
1122         ENTRY;
1123
1124         LINVRNT(osd_invariant(obj));
1125         LASSERT(obj->oo_inode == NULL);
1126
1127         if (fid_is_sane(fid) == 0) {
1128                 CERROR("%s: invalid FID "DFID"\n", ldev->ld_obd->obd_name,
1129                        PFID(fid));
1130                 dump_stack();
1131                 RETURN(-EINVAL);
1132         }
1133
1134         dev = osd_dev(ldev);
1135         scrub = &dev->od_scrub.os_scrub;
1136         sf = &scrub->os_file;
1137         info = osd_oti_get(env);
1138         LASSERT(info);
1139         oic = &info->oti_cache;
1140
1141         if (OBD_FAIL_CHECK(OBD_FAIL_SRV_ENOENT))
1142                 RETURN(-ENOENT);
1143
1144         /*
1145          * For the object is created as locking anchor, or for the object to
1146          * be created on disk. No need to osd_oi_lookup() at here because FID
1147          * shouldn't never be re-used, if it's really a duplicate FID from
1148          * unexpected reason, we should be able to detect it later by calling
1149          * do_create->osd_oi_insert().
1150          */
1151         if (conf && conf->loc_flags & LOC_F_NEW)
1152                 GOTO(out, result = 0);
1153
1154         /* Search order: 1. per-thread cache. */
1155         if (lu_fid_eq(fid, &oic->oic_fid) && likely(oic->oic_dev == dev)) {
1156                 id = &oic->oic_lid;
1157                 goto iget;
1158         }
1159
1160         id = &info->oti_id;
1161         memset(id, 0, sizeof(struct osd_inode_id));
1162         if (!list_empty(&scrub->os_inconsistent_items)) {
1163                 /* Search order: 2. OI scrub pending list. */
1164                 result = osd_oii_lookup(dev, fid, id);
1165                 if (!result)
1166                         goto iget;
1167         }
1168
1169         /*
1170          * The OI mapping in the OI file can be updated by the OI scrub
1171          * when we locate the inode via FID. So it may be not trustable.
1172          */
1173         trusted = false;
1174
1175         /* Search order: 3. OI files. */
1176         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1177         if (result == -ENOENT) {
1178                 if (!(fid_is_norm(fid) || fid_is_igif(fid)) ||
1179                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
1180                     !ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
1181                                       sf->sf_oi_bitmap))
1182                         GOTO(out, result = 0);
1183
1184                 goto trigger;
1185         }
1186
1187         /* -ESTALE is returned if inode of OST object doesn't exist */
1188         if (result == -ESTALE &&
1189             fid_is_on_ost(info, dev, fid, OI_CHECK_FLD)) {
1190                 GOTO(out, result = 0);
1191         }
1192
1193         if (result)
1194                 GOTO(out, result);
1195
1196 iget:
1197         obj->oo_inode = NULL;
1198         /* for later passes through checks, not true on first pass */
1199         if (!IS_ERR_OR_NULL(inode))
1200                 iput(inode);
1201
1202         inode = osd_iget_check(info, dev, fid, id, trusted);
1203         if (!IS_ERR(inode)) {
1204                 obj->oo_inode = inode;
1205                 result = 0;
1206                 if (remote)
1207                         goto trigger;
1208
1209                 goto check_lma;
1210         }
1211
1212         result = PTR_ERR(inode);
1213         if (result == -ENOENT || result == -ESTALE)
1214                 GOTO(out, result = 0);
1215
1216         if (result != -EREMCHG)
1217                 GOTO(out, result);
1218
1219 trigger:
1220         /*
1221          * We still have chance to get the valid inode: for the
1222          * object which is referenced by remote name entry, the
1223          * object on the local MDT will be linked under the dir
1224          * of "/REMOTE_PARENT_DIR" with its FID string as name.
1225          *
1226          * We do not know whether the object for the given FID
1227          * is referenced by some remote name entry or not, and
1228          * especially for DNE II, a multiple-linked object may
1229          * have many name entries reside on many MDTs.
1230          *
1231          * To simplify the operation, OSD will not distinguish
1232          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
1233          * only happened for the RPC from other MDT during the
1234          * OI scrub, or for the client side RPC with FID only,
1235          * such as FID to path, or from old connected client.
1236          */
1237         if (!remote) {
1238                 rc1 = osd_lookup_in_remote_parent(info, dev, fid, id);
1239                 if (!rc1) {
1240                         remote = true;
1241                         trusted = true;
1242                         flags |= SS_AUTO_PARTIAL;
1243                         flags &= ~SS_AUTO_FULL;
1244                         goto iget;
1245                 }
1246         }
1247
1248         if (scrub->os_running) {
1249                 if (scrub->os_partial_scan && !scrub->os_in_join)
1250                         goto join;
1251
1252                 if (IS_ERR_OR_NULL(inode) || result) {
1253                         osd_oii_insert(dev, fid, id, result == -ENOENT);
1254                         GOTO(out, result = -EINPROGRESS);
1255                 }
1256
1257                 LASSERT(remote);
1258                 LASSERT(obj->oo_inode == inode);
1259
1260                 osd_oii_insert(dev, fid, id, true);
1261                 goto found;
1262         }
1263
1264         if (dev->od_scrub.os_scrub.os_auto_scrub_interval == AS_NEVER) {
1265                 if (!remote)
1266                         GOTO(out, result = -EREMCHG);
1267
1268                 LASSERT(!result);
1269                 LASSERT(obj->oo_inode == inode);
1270
1271                 osd_add_oi_cache(info, dev, id, fid);
1272                 goto found;
1273         }
1274
1275 join:
1276         rc1 = osd_scrub_start(env, dev, flags);
1277         CDEBUG_LIMIT(D_LFSCK | D_CONSOLE | D_WARNING,
1278                      "%s: trigger OI scrub by RPC for "DFID"/%u with flags %#x: rc = %d\n",
1279                      osd_name(dev), PFID(fid), id->oii_ino, flags, rc1);
1280         if (rc1 && rc1 != -EALREADY)
1281                 GOTO(out, result = -EREMCHG);
1282
1283         if (IS_ERR_OR_NULL(inode) || result) {
1284                 osd_oii_insert(dev, fid, id, result == -ENOENT);
1285                 GOTO(out, result = -EINPROGRESS);
1286         }
1287
1288         LASSERT(remote);
1289         LASSERT(obj->oo_inode == inode);
1290
1291         osd_oii_insert(dev, fid, id, true);
1292         goto found;
1293
1294 check_lma:
1295         checked = true;
1296         if (unlikely(obj->oo_header))
1297                 goto found;
1298
1299         result = osd_check_lma(env, obj);
1300         if (!result)
1301                 goto found;
1302
1303         LASSERTF(id->oii_ino == inode->i_ino &&
1304                  id->oii_gen == inode->i_generation,
1305                  "locate wrong inode for FID: "DFID", %u/%u => %ld/%u\n",
1306                  PFID(fid), id->oii_ino, id->oii_gen,
1307                  inode->i_ino, inode->i_generation);
1308
1309         saved_ino = inode->i_ino;
1310         saved_gen = inode->i_generation;
1311
1312         if (unlikely(result == -ENODATA)) {
1313                 /*
1314                  * If the OI scrub updated the OI mapping by race, it
1315                  * must be valid. Trust the inode that has no LMA EA.
1316                  */
1317                 if (updated)
1318                         goto found;
1319
1320                 result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1321                 if (!result) {
1322                         /*
1323                          * The OI mapping is still there, the inode is still
1324                          * valid. It is just becaues the inode has no LMA EA.
1325                          */
1326                         if (saved_ino == id->oii_ino &&
1327                             saved_gen == id->oii_gen)
1328                                 goto found;
1329
1330                         /*
1331                          * It is the OI scrub updated the OI mapping by race.
1332                          * The new OI mapping must be valid.
1333                          */
1334                         trusted = true;
1335                         updated = true;
1336                         goto iget;
1337                 }
1338
1339                 /*
1340                  * "result == -ENOENT" means that the OI mappinghas been
1341                  * removed by race, so the inode belongs to other object.
1342                  *
1343                  * Others error can be returned  directly.
1344                  */
1345                 if (result == -ENOENT) {
1346                         LASSERT(trusted);
1347
1348                         obj->oo_inode = NULL;
1349                         result = 0;
1350                 }
1351         }
1352
1353         if (result != -EREMCHG)
1354                 GOTO(out, result);
1355
1356         LASSERT(!updated);
1357
1358         /*
1359          * if two OST objects map to the same inode, and inode mode is
1360          * (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666), which means it's
1361          * reserved by precreate, and not written yet, in this case, don't
1362          * set inode for the object whose FID mismatch, so that it can create
1363          * inode and not block precreate.
1364          */
1365         if (fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) &&
1366             inode->i_mode == (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666)) {
1367                 obj->oo_inode = NULL;
1368                 GOTO(out, result = 0);
1369         }
1370
1371         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1372         /*
1373          * "result == -ENOENT" means the cached OI mapping has been removed
1374          * from the OI file by race, above inode belongs to other object.
1375          */
1376         if (result == -ENOENT) {
1377                 LASSERT(trusted);
1378
1379                 obj->oo_inode = NULL;
1380                 GOTO(out, result = 0);
1381         }
1382
1383         if (result)
1384                 GOTO(out, result);
1385
1386         if (saved_ino == id->oii_ino && saved_gen == id->oii_gen) {
1387                 result = -EREMCHG;
1388                 osd_scrub_refresh_mapping(info, dev, fid, id, DTO_INDEX_DELETE,
1389                                           true, 0, NULL);
1390                 goto trigger;
1391         }
1392
1393         /*
1394          * It is the OI scrub updated the OI mapping by race.
1395          * The new OI mapping must be valid.
1396          */
1397         trusted = true;
1398         updated = true;
1399         goto iget;
1400
1401 found:
1402         if (!checked) {
1403                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
1404                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
1405
1406                 result = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
1407                 if (!result) {
1408                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
1409                             dev->od_is_ost)
1410                                 obj->oo_pfid_in_lma = 1;
1411                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
1412                             !dev->od_is_ost)
1413                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
1414                 } else if (result != -ENODATA) {
1415                         GOTO(out, result);
1416                 }
1417         }
1418
1419         obj->oo_compat_dot_created = 1;
1420         obj->oo_compat_dotdot_created = 1;
1421
1422         if (S_ISDIR(inode->i_mode) &&
1423             (flags & SS_AUTO_PARTIAL || sf->sf_status == SS_SCANNING))
1424                 osd_check_lmv(info, dev, inode);
1425
1426         result = osd_attach_jinode(inode);
1427         if (result)
1428                 GOTO(out, result);
1429
1430         if (!ldiskfs_pdo)
1431                 GOTO(out, result = 0);
1432
1433         LASSERT(!obj->oo_hl_head);
1434         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1435
1436         GOTO(out, result = (!obj->oo_hl_head ? -ENOMEM : 0));
1437
1438 out:
1439         if (result || !obj->oo_inode) {
1440                 if (!IS_ERR_OR_NULL(inode))
1441                         iput(inode);
1442
1443                 obj->oo_inode = NULL;
1444                 if (trusted)
1445                         fid_zero(&oic->oic_fid);
1446         }
1447
1448         LINVRNT(osd_invariant(obj));
1449         return result;
1450 }
1451
1452 /*
1453  * Concurrency: shouldn't matter.
1454  */
1455 static void osd_object_init0(struct osd_object *obj)
1456 {
1457         LASSERT(obj->oo_inode != NULL);
1458         obj->oo_dt.do_body_ops = &osd_body_ops;
1459         obj->oo_dt.do_lu.lo_header->loh_attr |=
1460                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
1461 }
1462
1463 /*
1464  * Concurrency: no concurrent access is possible that early in object
1465  * life-cycle.
1466  */
1467 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
1468                            const struct lu_object_conf *conf)
1469 {
1470         struct osd_object *obj = osd_obj(l);
1471         int result;
1472
1473         LINVRNT(osd_invariant(obj));
1474
1475         if (OBD_FAIL_PRECHECK(OBD_FAIL_MDS_LLOG_UMOUNT_RACE) &&
1476             cfs_fail_val == 2) {
1477                 struct osd_thread_info *info = osd_oti_get(env);
1478                 struct osd_idmap_cache *oic = &info->oti_cache;
1479                 /* invalidate thread cache */
1480                 memset(&oic->oic_fid, 0, sizeof(oic->oic_fid));
1481         }
1482         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
1483                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
1484                 l->lo_header->loh_attr |= LOHA_EXISTS;
1485                 return 0;
1486         }
1487
1488         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
1489         obj->oo_dt.do_body_ops = &osd_body_ops_new;
1490         if (result == 0 && obj->oo_inode != NULL) {
1491                 struct osd_thread_info *oti = osd_oti_get(env);
1492                 struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
1493
1494                 osd_object_init0(obj);
1495                 if (unlikely(obj->oo_header))
1496                         return 0;
1497
1498                 result = osd_get_lma(oti, obj->oo_inode,
1499                                      &oti->oti_obj_dentry, loa);
1500                 if (!result) {
1501                         /*
1502                          * Convert LMAI flags to lustre LMA flags
1503                          * and cache it to oo_lma_flags
1504                          */
1505                         obj->oo_lma_flags =
1506                                 lma_to_lustre_flags(loa->loa_lma.lma_incompat);
1507                 } else if (result == -ENODATA) {
1508                         result = 0;
1509                 }
1510         }
1511         obj->oo_dirent_count = LU_DIRENT_COUNT_UNSET;
1512
1513         LINVRNT(osd_invariant(obj));
1514         return result;
1515 }
1516
1517 /*
1518  * The first part of oxe_buf is xattr name, and is '\0' terminated.
1519  * The left part is for value, binary mode.
1520  */
1521 struct osd_xattr_entry {
1522         struct list_head        oxe_list;
1523         size_t                  oxe_len;
1524         size_t                  oxe_namelen;
1525         bool                    oxe_exist;
1526         struct rcu_head         oxe_rcu;
1527         char                    oxe_buf[0];
1528 };
1529
1530 static int osd_oxc_get(struct osd_object *obj, const char *name,
1531                        struct lu_buf *buf)
1532 {
1533         struct osd_xattr_entry *tmp;
1534         struct osd_xattr_entry *oxe = NULL;
1535         size_t namelen = strlen(name);
1536         int rc;
1537
1538         rcu_read_lock();
1539         list_for_each_entry_rcu(tmp, &obj->oo_xattr_list, oxe_list) {
1540                 if (namelen == tmp->oxe_namelen &&
1541                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1542                         oxe = tmp;
1543                         break;
1544                 }
1545         }
1546
1547         if (oxe == NULL)
1548                 GOTO(out, rc = -ENOENT);
1549
1550         if (!oxe->oxe_exist)
1551                 GOTO(out, rc = -ENODATA);
1552
1553         /* vallen */
1554         rc = oxe->oxe_len - sizeof(*oxe) - oxe->oxe_namelen - 1;
1555         LASSERT(rc > 0);
1556
1557         if (buf->lb_buf == NULL)
1558                 GOTO(out, rc);
1559
1560         if (buf->lb_len < rc)
1561                 GOTO(out, rc = -ERANGE);
1562
1563         memcpy(buf->lb_buf, &oxe->oxe_buf[namelen + 1], rc);
1564 out:
1565         rcu_read_unlock();
1566
1567         return rc;
1568 }
1569
1570 static void osd_oxc_free(struct rcu_head *head)
1571 {
1572         struct osd_xattr_entry *oxe;
1573
1574         oxe = container_of(head, struct osd_xattr_entry, oxe_rcu);
1575         OBD_FREE(oxe, oxe->oxe_len);
1576 }
1577
1578 static void osd_oxc_add(struct osd_object *obj, const char *name,
1579                         const char *buf, int buflen)
1580 {
1581         struct osd_xattr_entry *oxe;
1582         struct osd_xattr_entry *old = NULL;
1583         struct osd_xattr_entry *tmp;
1584         size_t namelen = strlen(name);
1585         size_t len = sizeof(*oxe) + namelen + 1 + buflen;
1586
1587         OBD_ALLOC(oxe, len);
1588         if (oxe == NULL)
1589                 return;
1590
1591         INIT_LIST_HEAD(&oxe->oxe_list);
1592         oxe->oxe_len = len;
1593         oxe->oxe_namelen = namelen;
1594         memcpy(oxe->oxe_buf, name, namelen);
1595         if (buflen > 0) {
1596                 LASSERT(buf != NULL);
1597                 memcpy(oxe->oxe_buf + namelen + 1, buf, buflen);
1598                 oxe->oxe_exist = true;
1599         } else {
1600                 oxe->oxe_exist = false;
1601         }
1602
1603         /* this should be rarely called, just remove old and add new */
1604         spin_lock(&obj->oo_guard);
1605         list_for_each_entry(tmp, &obj->oo_xattr_list, oxe_list) {
1606                 if (namelen == tmp->oxe_namelen &&
1607                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1608                         old = tmp;
1609                         break;
1610                 }
1611         }
1612         if (old != NULL) {
1613                 list_replace_rcu(&old->oxe_list, &oxe->oxe_list);
1614                 call_rcu(&old->oxe_rcu, osd_oxc_free);
1615         } else {
1616                 list_add_tail_rcu(&oxe->oxe_list, &obj->oo_xattr_list);
1617         }
1618         spin_unlock(&obj->oo_guard);
1619 }
1620
1621 static void osd_oxc_del(struct osd_object *obj, const char *name)
1622 {
1623         struct osd_xattr_entry *oxe;
1624         size_t namelen = strlen(name);
1625
1626         spin_lock(&obj->oo_guard);
1627         list_for_each_entry(oxe, &obj->oo_xattr_list, oxe_list) {
1628                 if (namelen == oxe->oxe_namelen &&
1629                     strncmp(name, oxe->oxe_buf, namelen) == 0) {
1630                         list_del_rcu(&oxe->oxe_list);
1631                         call_rcu(&oxe->oxe_rcu, osd_oxc_free);
1632                         break;
1633                 }
1634         }
1635         spin_unlock(&obj->oo_guard);
1636 }
1637
1638 static void osd_oxc_fini(struct osd_object *obj)
1639 {
1640         struct osd_xattr_entry *oxe, *next;
1641
1642         list_for_each_entry_safe(oxe, next, &obj->oo_xattr_list, oxe_list) {
1643                 list_del(&oxe->oxe_list);
1644                 OBD_FREE(oxe, oxe->oxe_len);
1645         }
1646 }
1647
1648 /*
1649  * Concurrency: no concurrent access is possible that late in object
1650  * life-cycle.
1651  */
1652 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
1653 {
1654         struct osd_object *obj = osd_obj(l);
1655         struct lu_object_header *h = obj->oo_header;
1656
1657         LINVRNT(osd_invariant(obj));
1658
1659         osd_oxc_fini(obj);
1660         dt_object_fini(&obj->oo_dt);
1661         if (obj->oo_hl_head != NULL)
1662                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1663         /* obj doesn't contain an lu_object_header, so we don't need call_rcu */
1664         OBD_FREE_PTR(obj);
1665         if (unlikely(h))
1666                 lu_object_header_free(h);
1667 }
1668
1669 /*
1670  * Concurrency: no concurrent access is possible that late in object
1671  * life-cycle.
1672  */
1673 static void osd_index_fini(struct osd_object *o)
1674 {
1675         struct iam_container *bag;
1676
1677         if (o->oo_dir != NULL) {
1678                 bag = &o->oo_dir->od_container;
1679                 if (o->oo_inode != NULL) {
1680                         if (bag->ic_object == o->oo_inode)
1681                                 iam_container_fini(bag);
1682                 }
1683                 OBD_FREE_PTR(o->oo_dir);
1684                 o->oo_dir = NULL;
1685         }
1686 }
1687
1688 enum {
1689         OSD_TXN_OI_DELETE_CREDITS    = 20,
1690         OSD_TXN_INODE_DELETE_CREDITS = 20
1691 };
1692
1693 /*
1694  * Journal
1695  */
1696
1697 #if OSD_THANDLE_STATS
1698 /**
1699  * Set time when the handle is allocated
1700  */
1701 static void osd_th_alloced(struct osd_thandle *oth)
1702 {
1703         oth->oth_alloced = ktime_get();
1704 }
1705
1706 /**
1707  * Set time when the handle started
1708  */
1709 static void osd_th_started(struct osd_thandle *oth)
1710 {
1711         oth->oth_started = ktime_get();
1712 }
1713
1714 /**
1715  * Check whether the we deal with this handle for too long.
1716  */
1717 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
1718                                 ktime_t alloced, ktime_t started,
1719                                 ktime_t closed)
1720 {
1721         ktime_t now = ktime_get();
1722
1723         LASSERT(dev != NULL);
1724
1725         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
1726                             ktime_us_delta(started, alloced));
1727         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
1728                             ktime_us_delta(closed, started));
1729         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
1730                             ktime_us_delta(now, closed));
1731
1732         if (ktime_before(ktime_add_ns(alloced, 30 * NSEC_PER_SEC), now)) {
1733                 CWARN("transaction handle %p was open for too long: now %lld, alloced %lld, started %lld, closed %lld\n",
1734                                 oth, now, alloced, started, closed);
1735                 libcfs_debug_dumpstack(NULL);
1736         }
1737 }
1738
1739 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
1740 {                                                                       \
1741         ktime_t __closed = ktime_get();                                 \
1742         ktime_t __alloced = oth->oth_alloced;                           \
1743         ktime_t __started = oth->oth_started;                           \
1744                                                                         \
1745         expr;                                                           \
1746         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
1747 }
1748
1749 #else /* OSD_THANDLE_STATS */
1750
1751 #define osd_th_alloced(h)                  do {} while(0)
1752 #define osd_th_started(h)                  do {} while(0)
1753 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
1754
1755 #endif /* OSD_THANDLE_STATS */
1756
1757 /*
1758  * Concurrency: doesn't access mutable data.
1759  */
1760 static int osd_param_is_not_sane(const struct osd_device *dev,
1761                                  const struct thandle *th)
1762 {
1763         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
1764
1765         return oh->ot_credits > osd_transaction_size(dev);
1766 }
1767
1768 /*
1769  * Concurrency: shouldn't matter.
1770  */
1771 static void osd_trans_commit_cb(struct super_block *sb,
1772                                 struct ldiskfs_journal_cb_entry *jcb, int error)
1773 {
1774         struct osd_thandle *oh = container_of(jcb, struct osd_thandle, ot_jcb);
1775         struct thandle *th = &oh->ot_super;
1776         struct lu_device *lud = &th->th_dev->dd_lu_dev;
1777         struct osd_device *osd = osd_dev(lud);
1778         struct dt_txn_commit_cb *dcb, *tmp;
1779
1780         LASSERT(oh->ot_handle == NULL);
1781
1782         if (error)
1783                 CERROR("transaction @0x%p commit error: %d\n", th, error);
1784
1785         OBD_FAIL_TIMEOUT(OBD_FAIL_OST_DELAY_TRANS, 40);
1786         /* call per-transaction callbacks if any */
1787         list_for_each_entry_safe(dcb, tmp, &oh->ot_commit_dcb_list,
1788                                  dcb_linkage) {
1789                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1790                          "commit callback entry: magic=%x name='%s'\n",
1791                          dcb->dcb_magic, dcb->dcb_name);
1792                 list_del_init(&dcb->dcb_linkage);
1793                 dcb->dcb_func(NULL, th, dcb, error);
1794         }
1795
1796         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
1797         if (atomic_dec_and_test(&osd->od_commit_cb_in_flight))
1798                 wake_up(&osd->od_commit_cb_done);
1799         th->th_dev = NULL;
1800
1801         OBD_FREE_PTR(oh);
1802 }
1803
1804 static struct thandle *osd_trans_create(const struct lu_env *env,
1805                                         struct dt_device *d)
1806 {
1807         struct osd_thread_info *oti = osd_oti_get(env);
1808         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1809         struct osd_thandle *oh;
1810         struct thandle *th;
1811
1812         ENTRY;
1813
1814         if (d->dd_rdonly) {
1815                 CERROR("%s: someone try to start transaction under "
1816                        "readonly mode, should be disabled.\n",
1817                        osd_name(osd_dt_dev(d)));
1818                 dump_stack();
1819                 RETURN(ERR_PTR(-EROFS));
1820         }
1821
1822         /* on pending IO in this thread should left from prev. request */
1823         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
1824
1825         sb_start_write(osd_sb(osd_dt_dev(d)));
1826
1827         OBD_ALLOC_GFP(oh, sizeof(*oh), GFP_NOFS);
1828         if (!oh) {
1829                 sb_end_write(osd_sb(osd_dt_dev(d)));
1830                 RETURN(ERR_PTR(-ENOMEM));
1831         }
1832
1833         oh->ot_quota_trans = &oti->oti_quota_trans;
1834         memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
1835         th = &oh->ot_super;
1836         th->th_dev = d;
1837         th->th_result = 0;
1838         oh->ot_credits = 0;
1839         oh->oh_declared_ext = 0;
1840         INIT_LIST_HEAD(&oh->ot_commit_dcb_list);
1841         INIT_LIST_HEAD(&oh->ot_stop_dcb_list);
1842         INIT_LIST_HEAD(&oh->ot_trunc_locks);
1843         osd_th_alloced(oh);
1844
1845         memset(oti->oti_declare_ops, 0,
1846                sizeof(oti->oti_declare_ops));
1847         memset(oti->oti_declare_ops_cred, 0,
1848                sizeof(oti->oti_declare_ops_cred));
1849         memset(oti->oti_declare_ops_used, 0,
1850                sizeof(oti->oti_declare_ops_used));
1851
1852         oti->oti_ins_cache_depth++;
1853
1854         RETURN(th);
1855 }
1856
1857 void osd_trans_dump_creds(const struct lu_env *env, struct thandle *th)
1858 {
1859         struct osd_thread_info *oti = osd_oti_get(env);
1860         struct osd_thandle *oh;
1861
1862         oh = container_of(th, struct osd_thandle, ot_super);
1863         LASSERT(oh != NULL);
1864
1865         CWARN("  create: %u/%u/%u, destroy: %u/%u/%u\n",
1866               oti->oti_declare_ops[OSD_OT_CREATE],
1867               oti->oti_declare_ops_cred[OSD_OT_CREATE],
1868               oti->oti_declare_ops_used[OSD_OT_CREATE],
1869               oti->oti_declare_ops[OSD_OT_DESTROY],
1870               oti->oti_declare_ops_cred[OSD_OT_DESTROY],
1871               oti->oti_declare_ops_used[OSD_OT_DESTROY]);
1872         CWARN("  attr_set: %u/%u/%u, xattr_set: %u/%u/%u\n",
1873               oti->oti_declare_ops[OSD_OT_ATTR_SET],
1874               oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1875               oti->oti_declare_ops_used[OSD_OT_ATTR_SET],
1876               oti->oti_declare_ops[OSD_OT_XATTR_SET],
1877               oti->oti_declare_ops_cred[OSD_OT_XATTR_SET],
1878               oti->oti_declare_ops_used[OSD_OT_XATTR_SET]);
1879         CWARN("  write: %u/%u/%u, punch: %u/%u/%u, quota %u/%u/%u\n",
1880               oti->oti_declare_ops[OSD_OT_WRITE],
1881               oti->oti_declare_ops_cred[OSD_OT_WRITE],
1882               oti->oti_declare_ops_used[OSD_OT_WRITE],
1883               oti->oti_declare_ops[OSD_OT_PUNCH],
1884               oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1885               oti->oti_declare_ops_used[OSD_OT_PUNCH],
1886               oti->oti_declare_ops[OSD_OT_QUOTA],
1887               oti->oti_declare_ops_cred[OSD_OT_QUOTA],
1888               oti->oti_declare_ops_used[OSD_OT_QUOTA]);
1889         CWARN("  insert: %u/%u/%u, delete: %u/%u/%u\n",
1890               oti->oti_declare_ops[OSD_OT_INSERT],
1891               oti->oti_declare_ops_cred[OSD_OT_INSERT],
1892               oti->oti_declare_ops_used[OSD_OT_INSERT],
1893               oti->oti_declare_ops[OSD_OT_DELETE],
1894               oti->oti_declare_ops_cred[OSD_OT_DELETE],
1895               oti->oti_declare_ops_used[OSD_OT_DELETE]);
1896         CWARN("  ref_add: %u/%u/%u, ref_del: %u/%u/%u\n",
1897               oti->oti_declare_ops[OSD_OT_REF_ADD],
1898               oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1899               oti->oti_declare_ops_used[OSD_OT_REF_ADD],
1900               oti->oti_declare_ops[OSD_OT_REF_DEL],
1901               oti->oti_declare_ops_cred[OSD_OT_REF_DEL],
1902               oti->oti_declare_ops_used[OSD_OT_REF_DEL]);
1903 }
1904
1905 /*
1906  * Concurrency: shouldn't matter.
1907  */
1908 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
1909                            struct thandle *th)
1910 {
1911         struct osd_thread_info *oti = osd_oti_get(env);
1912         struct osd_device *dev = osd_dt_dev(d);
1913         handle_t *jh;
1914         struct osd_thandle *oh;
1915         int rc;
1916
1917         ENTRY;
1918
1919         LASSERT(current->journal_info == NULL);
1920
1921         oh = container_of(th, struct osd_thandle, ot_super);
1922         LASSERT(oh != NULL);
1923         LASSERT(oh->ot_handle == NULL);
1924
1925         rc = dt_txn_hook_start(env, d, th);
1926         if (rc != 0)
1927                 GOTO(out, rc);
1928
1929         if (unlikely(osd_param_is_not_sane(dev, th))) {
1930                 static unsigned long last_printed;
1931                 static int last_credits;
1932
1933                 /*
1934                  * don't make noise on a tiny testing systems
1935                  * actual credits misuse will be caught anyway
1936                  */
1937                 if (last_credits != oh->ot_credits &&
1938                     time_after(jiffies, last_printed +
1939                                cfs_time_seconds(60)) &&
1940                     osd_transaction_size(dev) > 512) {
1941                         CWARN("%s: credits %u > trans_max %u\n", osd_name(dev),
1942                               oh->ot_credits, osd_transaction_size(dev));
1943                         osd_trans_dump_creds(env, th);
1944                         libcfs_debug_dumpstack(NULL);
1945                         last_credits = oh->ot_credits;
1946                         last_printed = jiffies;
1947                 }
1948                 /*
1949                  * XXX Limit the credits to 'max_transaction_buffers', and
1950                  *     let the underlying filesystem to catch the error if
1951                  *     we really need so many credits.
1952                  *
1953                  *     This should be removed when we can calculate the
1954                  *     credits precisely.
1955                  */
1956                 oh->ot_credits = osd_transaction_size(dev);
1957         } else if (ldiskfs_track_declares_assert != 0) {
1958                 /*
1959                  * reserve few credits to prevent an assertion in JBD
1960                  * our debugging mechanism will be able to detected
1961                  * overuse. this can help to debug single-update
1962                  * transactions
1963                  */
1964                 oh->ot_credits += 10;
1965                 if (unlikely(osd_param_is_not_sane(dev, th)))
1966                         oh->ot_credits = osd_transaction_size(dev);
1967         }
1968
1969         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_TXN_START))
1970                 GOTO(out, rc = -EIO);
1971
1972         /*
1973          * XXX temporary stuff. Some abstraction layer should
1974          * be used.
1975          */
1976         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
1977         osd_th_started(oh);
1978         if (!IS_ERR(jh)) {
1979                 oh->ot_handle = jh;
1980                 LASSERT(oti->oti_txns == 0);
1981
1982                 atomic_inc(&dev->od_commit_cb_in_flight);
1983                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
1984                               "osd-tx", th);
1985                 oti->oti_txns++;
1986                 rc = 0;
1987         } else {
1988                 rc = PTR_ERR(jh);
1989         }
1990 out:
1991         RETURN(rc);
1992 }
1993
1994 static int osd_seq_exists(const struct lu_env *env,
1995                           struct osd_device *osd, u64 seq)
1996 {
1997         struct lu_seq_range *range = &osd_oti_get(env)->oti_seq_range;
1998         struct seq_server_site *ss = osd_seq_site(osd);
1999         int rc;
2000
2001         ENTRY;
2002
2003         LASSERT(ss != NULL);
2004         LASSERT(ss->ss_server_fld != NULL);
2005
2006         rc = osd_fld_lookup(env, osd, seq, range);
2007         if (rc != 0) {
2008                 if (rc != -ENOENT)
2009                         CERROR("%s: can't lookup FLD sequence %#llx: rc = %d\n",
2010                                osd_name(osd), seq, rc);
2011                 RETURN(0);
2012         }
2013
2014         RETURN(ss->ss_node_id == range->lsr_index);
2015 }
2016
2017 static void osd_trans_stop_cb(struct osd_thandle *oth, int result)
2018 {
2019         struct dt_txn_commit_cb *dcb;
2020         struct dt_txn_commit_cb *tmp;
2021
2022         /* call per-transaction stop callbacks if any */
2023         list_for_each_entry_safe(dcb, tmp, &oth->ot_stop_dcb_list,
2024                                  dcb_linkage) {
2025                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
2026                          "commit callback entry: magic=%x name='%s'\n",
2027                          dcb->dcb_magic, dcb->dcb_name);
2028                 list_del_init(&dcb->dcb_linkage);
2029                 dcb->dcb_func(NULL, &oth->ot_super, dcb, result);
2030         }
2031 }
2032
2033 /*
2034  * Concurrency: shouldn't matter.
2035  */
2036 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
2037                           struct thandle *th)
2038 {
2039         struct osd_thread_info *oti = osd_oti_get(env);
2040         struct osd_thandle *oh;
2041         struct osd_iobuf *iobuf = &oti->oti_iobuf;
2042         struct osd_device *osd = osd_dt_dev(th->th_dev);
2043         struct qsd_instance *qsd = osd_def_qsd(osd);
2044         struct lquota_trans *qtrans;
2045         LIST_HEAD(truncates);
2046         int rc = 0, remove_agents = 0;
2047
2048         ENTRY;
2049
2050         oh = container_of(th, struct osd_thandle, ot_super);
2051
2052         remove_agents = oh->ot_remove_agents;
2053
2054         qtrans = oh->ot_quota_trans;
2055         oh->ot_quota_trans = NULL;
2056
2057         /* move locks to local list, stop tx, execute truncates */
2058         list_splice(&oh->ot_trunc_locks, &truncates);
2059
2060         if (oh->ot_handle != NULL) {
2061                 int rc2;
2062
2063                 handle_t *hdl = oh->ot_handle;
2064
2065                 /*
2066                  * add commit callback
2067                  * notice we don't do this in osd_trans_start()
2068                  * as underlying transaction can change during truncate
2069                  */
2070                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
2071                                              &oh->ot_jcb);
2072
2073                 LASSERT(oti->oti_txns == 1);
2074                 oti->oti_txns--;
2075
2076                 rc = dt_txn_hook_stop(env, th);
2077                 if (rc != 0)
2078                         CERROR("%s: failed in transaction hook: rc = %d\n",
2079                                osd_name(osd), rc);
2080
2081                 osd_trans_stop_cb(oh, rc);
2082                 /* hook functions might modify th_sync */
2083                 hdl->h_sync = th->th_sync;
2084
2085                 oh->ot_handle = NULL;
2086                 OSD_CHECK_SLOW_TH(oh, osd, rc2 = ldiskfs_journal_stop(hdl));
2087                 if (rc2 != 0)
2088                         CERROR("%s: failed to stop transaction: rc = %d\n",
2089                                osd_name(osd), rc2);
2090                 if (!rc)
2091                         rc = rc2;
2092
2093                 osd_process_truncates(env, &truncates);
2094         } else {
2095                 osd_trans_stop_cb(oh, th->th_result);
2096                 OBD_FREE_PTR(oh);
2097         }
2098
2099         osd_trunc_unlock_all(env, &truncates);
2100
2101         /* inform the quota slave device that the transaction is stopping */
2102         qsd_op_end(env, qsd, qtrans);
2103
2104         /*
2105          * as we want IO to journal and data IO be concurrent, we don't block
2106          * awaiting data IO completion in osd_do_bio(), instead we wait here
2107          * once transaction is submitted to the journal. all reqular requests
2108          * don't do direct IO (except read/write), thus this wait_event becomes
2109          * no-op for them.
2110          *
2111          * IMPORTANT: we have to wait till any IO submited by the thread is
2112          * completed otherwise iobuf may be corrupted by different request
2113          */
2114         wait_event(iobuf->dr_wait,
2115                        atomic_read(&iobuf->dr_numreqs) == 0);
2116         osd_fini_iobuf(osd, iobuf);
2117         if (!rc)
2118                 rc = iobuf->dr_error;
2119
2120         if (unlikely(remove_agents != 0))
2121                 osd_process_scheduled_agent_removals(env, osd);
2122
2123         LASSERT(oti->oti_ins_cache_depth > 0);
2124         oti->oti_ins_cache_depth--;
2125         /* reset OI cache for safety */
2126         if (oti->oti_ins_cache_depth == 0)
2127                 oti->oti_ins_cache_used = 0;
2128
2129         sb_end_write(osd_sb(osd));
2130
2131         RETURN(rc);
2132 }
2133
2134 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
2135 {
2136         struct osd_thandle *oh = container_of(th, struct osd_thandle,
2137                                               ot_super);
2138
2139         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
2140         LASSERT(&dcb->dcb_func != NULL);
2141         if (dcb->dcb_flags & DCB_TRANS_STOP)
2142                 list_add(&dcb->dcb_linkage, &oh->ot_stop_dcb_list);
2143         else
2144                 list_add(&dcb->dcb_linkage, &oh->ot_commit_dcb_list);
2145
2146         return 0;
2147 }
2148
2149 /*
2150  * Called just before object is freed. Releases all resources except for
2151  * object itself (that is released by osd_object_free()).
2152  *
2153  * Concurrency: no concurrent access is possible that late in object
2154  * life-cycle.
2155  */
2156 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
2157 {
2158         struct osd_object *obj = osd_obj(l);
2159         struct qsd_instance *qsd = osd_def_qsd(osd_obj2dev(obj));
2160         struct inode *inode = obj->oo_inode;
2161         __u64 projid;
2162         qid_t uid;
2163         qid_t gid;
2164
2165         LINVRNT(osd_invariant(obj));
2166
2167         /*
2168          * If object is unlinked remove fid->ino mapping from object index.
2169          */
2170
2171         osd_index_fini(obj);
2172
2173         if (!inode)
2174                 return;
2175
2176         if (osd_has_index(obj) &&  obj->oo_dt.do_index_ops == &osd_index_iam_ops)
2177                 ldiskfs_set_inode_flag(inode, LDISKFS_INODE_JOURNAL_DATA);
2178
2179         uid = i_uid_read(inode);
2180         gid = i_gid_read(inode);
2181         projid = i_projid_read(inode);
2182
2183         obj->oo_inode = NULL;
2184         iput(inode);
2185
2186         /* do not rebalance quota if the caller needs to release memory
2187          * otherwise qsd_refresh_usage() may went into a new ldiskfs
2188          * transaction and risk to deadlock - LU-12178 */
2189         if (current->flags & (PF_MEMALLOC | PF_KSWAPD))
2190                 return;
2191
2192         if (!obj->oo_header && qsd) {
2193                 struct osd_thread_info *info = osd_oti_get(env);
2194                 struct lquota_id_info *qi = &info->oti_qi;
2195
2196                 /* Release granted quota to master if necessary */
2197                 qi->lqi_id.qid_uid = uid;
2198                 qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
2199
2200                 qi->lqi_id.qid_uid = gid;
2201                 qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
2202
2203                 qi->lqi_id.qid_uid = projid;
2204                 qsd_op_adjust(env, qsd, &qi->lqi_id, PRJQUOTA);
2205         }
2206 }
2207
2208 /*
2209  * Concurrency: ->loo_object_release() is called under site spin-lock.
2210  */
2211 static void osd_object_release(const struct lu_env *env,
2212                                struct lu_object *l)
2213 {
2214         struct osd_object *o = osd_obj(l);
2215
2216         /*
2217          * nobody should be releasing a non-destroyed object with nlink=0
2218          * the API allows this, but ldiskfs doesn't like and then report
2219          * this inode as deleted
2220          */
2221         LASSERT(!(o->oo_destroyed == 0 && o->oo_inode &&
2222                   o->oo_inode->i_nlink == 0));
2223 }
2224
2225 /*
2226  * Concurrency: shouldn't matter.
2227  */
2228 static int osd_object_print(const struct lu_env *env, void *cookie,
2229                             lu_printer_t p, const struct lu_object *l)
2230 {
2231         struct osd_object *o = osd_obj(l);
2232         struct iam_descr *d;
2233
2234         if (o->oo_dir != NULL)
2235                 d = o->oo_dir->od_container.ic_descr;
2236         else
2237                 d = NULL;
2238         return (*p)(env, cookie,
2239                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
2240                     o, o->oo_inode,
2241                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
2242                     o->oo_inode ? o->oo_inode->i_generation : 0,
2243                     d ? d->id_ops->id_name : "plain");
2244 }
2245
2246 /*
2247  * Concurrency: shouldn't matter.
2248  */
2249 int osd_statfs(const struct lu_env *env, struct dt_device *d,
2250                 struct obd_statfs *sfs, struct obd_statfs_info *info)
2251 {
2252         struct osd_device *osd = osd_dt_dev(d);
2253         struct super_block *sb = osd_sb(osd);
2254         struct kstatfs *ksfs;
2255         __u64 reserved;
2256         int result = 0;
2257
2258         if (unlikely(osd->od_mnt == NULL))
2259                 return -EINPROGRESS;
2260
2261         /* osd_lproc.c call this without env, allocate ksfs for that case */
2262         if (unlikely(env == NULL)) {
2263                 OBD_ALLOC_PTR(ksfs);
2264                 if (ksfs == NULL)
2265                         return -ENOMEM;
2266         } else {
2267                 ksfs = &osd_oti_get(env)->oti_ksfs;
2268         }
2269
2270         result = sb->s_op->statfs(sb->s_root, ksfs);
2271         if (result)
2272                 goto out;
2273
2274         statfs_pack(sfs, ksfs);
2275         if (unlikely(sb->s_flags & SB_RDONLY))
2276                 sfs->os_state |= OS_STATFS_READONLY;
2277
2278         sfs->os_state |= osd->od_nonrotational ? OS_STATFS_NONROT : 0;
2279
2280         if (ldiskfs_has_feature_extents(sb))
2281                 sfs->os_maxbytes = sb->s_maxbytes;
2282         else
2283                 sfs->os_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2284
2285         /*
2286          * Reserve some space so to avoid fragmenting the filesystem too much.
2287          * Fragmentation not only impacts performance, but can also increase
2288          * metadata overhead significantly, causing grant calculation to be
2289          * wrong.
2290          *
2291          * Reserve 0.78% of total space, at least 8MB for small filesystems.
2292          */
2293         BUILD_BUG_ON(OSD_STATFS_RESERVED <= LDISKFS_MAX_BLOCK_SIZE);
2294         reserved = OSD_STATFS_RESERVED >> sb->s_blocksize_bits;
2295         if (likely(sfs->os_blocks >= reserved << OSD_STATFS_RESERVED_SHIFT))
2296                 reserved = sfs->os_blocks >> OSD_STATFS_RESERVED_SHIFT;
2297
2298         sfs->os_blocks -= reserved;
2299         sfs->os_bfree  -= min(reserved, sfs->os_bfree);
2300         sfs->os_bavail -= min(reserved, sfs->os_bavail);
2301
2302 out:
2303         if (unlikely(env == NULL))
2304                 OBD_FREE_PTR(ksfs);
2305         return result;
2306 }
2307
2308 /**
2309  * Estimate space needed for file creations. We assume the largest filename
2310  * which is 2^64 - 1, hence a filename of 20 chars.
2311  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
2312  */
2313 #ifdef __LDISKFS_DIR_REC_LEN
2314 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
2315 #else
2316 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
2317 #endif
2318
2319 /*
2320  * Concurrency: doesn't access mutable data.
2321  */
2322 static void osd_conf_get(const struct lu_env *env,
2323                          const struct dt_device *dev,
2324                          struct dt_device_param *param)
2325 {
2326         struct osd_device *d = osd_dt_dev(dev);
2327         struct super_block *sb = osd_sb(d);
2328         struct blk_integrity *bi = bdev_get_integrity(sb->s_bdev);
2329         const char *name;
2330         int ea_overhead;
2331
2332         /*
2333          * XXX should be taken from not-yet-existing fs abstraction layer.
2334          */
2335         param->ddp_max_name_len = LDISKFS_NAME_LEN;
2336         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
2337         param->ddp_symlink_max  = sb->s_blocksize;
2338         param->ddp_mount_type   = LDD_MT_LDISKFS;
2339         if (ldiskfs_has_feature_extents(sb))
2340                 param->ddp_maxbytes = sb->s_maxbytes;
2341         else
2342                 param->ddp_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2343         /*
2344          * inode are statically allocated, so per-inode space consumption
2345          * is the space consumed by the directory entry
2346          */
2347         param->ddp_inodespace     = PER_OBJ_USAGE;
2348         /*
2349          * EXT_INIT_MAX_LEN is the theoretical maximum extent size (32k blocks
2350          * is 128MB) which is unlikely to be hit in real life. Report a smaller
2351          * maximum length to not under-count the actual number of extents
2352          * needed for writing a file if there are sub-optimal block allocations.
2353          */
2354         param->ddp_max_extent_blks = EXT_INIT_MAX_LEN >> 1;
2355         /* worst-case extent insertion metadata overhead */
2356         param->ddp_extent_tax = 6 * LDISKFS_BLOCK_SIZE(sb);
2357         param->ddp_mntopts = 0;
2358         if (test_opt(sb, XATTR_USER))
2359                 param->ddp_mntopts |= MNTOPT_USERXATTR;
2360         if (test_opt(sb, POSIX_ACL))
2361                 param->ddp_mntopts |= MNTOPT_ACL;
2362
2363         /*
2364          * LOD might calculate the max stripe count based on max_ea_size,
2365          * so we need take account in the overhead as well,
2366          * xattr_header + magic + xattr_entry_head
2367          */
2368         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
2369                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
2370
2371 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
2372         if (ldiskfs_has_feature_ea_inode(sb))
2373                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
2374                                                                 ea_overhead;
2375         else
2376 #endif
2377                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
2378
2379         if (param->ddp_max_ea_size > OBD_MAX_EA_SIZE)
2380                 param->ddp_max_ea_size = OBD_MAX_EA_SIZE;
2381
2382         /*
2383          * Preferred RPC size for efficient disk IO.  4MB shows good
2384          * all-around performance for ldiskfs, but use bigalloc chunk size
2385          * by default if larger.
2386          */
2387 #if defined(LDISKFS_CLUSTER_SIZE)
2388         if (LDISKFS_CLUSTER_SIZE(sb) > DT_DEF_BRW_SIZE)
2389                 param->ddp_brw_size = LDISKFS_CLUSTER_SIZE(sb);
2390         else
2391 #endif
2392                 param->ddp_brw_size = DT_DEF_BRW_SIZE;
2393
2394         param->ddp_t10_cksum_type = 0;
2395         if (bi) {
2396                 unsigned short interval = blk_integrity_interval(bi);
2397                 name = blk_integrity_name(bi);
2398                 /*
2399                  * Expected values:
2400                  * T10-DIF-TYPE1-CRC
2401                  * T10-DIF-TYPE3-CRC
2402                  * T10-DIF-TYPE1-IP
2403                  * T10-DIF-TYPE3-IP
2404                  */
2405                 if (strncmp(name, "T10-DIF-TYPE",
2406                             sizeof("T10-DIF-TYPE") - 1) == 0) {
2407                         /* also skip "1/3-" at end */
2408                         const int type_off = sizeof("T10-DIF-TYPE.");
2409                         char type_number = name[type_off - 2];
2410
2411                         if (interval != 512 && interval != 4096) {
2412                                 CERROR("%s: unsupported T10PI sector size %u\n",
2413                                        d->od_svname, interval);
2414                         } else if (type_number != '1' && type_number != '3') {
2415                                 CERROR("%s: unsupported T10PI type %s\n",
2416                                        d->od_svname, name);
2417                         } else if (strcmp(name + type_off, "CRC") == 0) {
2418                                 d->od_t10_type = type_number == '1' ?
2419                                         OSD_T10_TYPE1_CRC : OSD_T10_TYPE3_CRC;
2420                                 param->ddp_t10_cksum_type = interval == 512 ?
2421                                         OBD_CKSUM_T10CRC512 :
2422                                         OBD_CKSUM_T10CRC4K;
2423                         } else if (strcmp(name + type_off, "IP") == 0) {
2424                                 d->od_t10_type = type_number == '1' ?
2425                                         OSD_T10_TYPE1_IP : OSD_T10_TYPE3_IP;
2426                                 param->ddp_t10_cksum_type = interval == 512 ?
2427                                         OBD_CKSUM_T10IP512 :
2428                                         OBD_CKSUM_T10IP4K;
2429                         } else {
2430                                 CERROR("%s: unsupported checksum type of T10PI type '%s'\n",
2431                                        d->od_svname, name);
2432                         }
2433
2434                 } else {
2435                         CERROR("%s: unsupported T10PI type '%s'\n",
2436                                d->od_svname, name);
2437                 }
2438         }
2439
2440         param->ddp_has_lseek_data_hole = true;
2441 }
2442
2443 static struct super_block *osd_mnt_sb_get(const struct dt_device *d)
2444 {
2445         return osd_sb(osd_dt_dev(d));
2446 }
2447
2448 /*
2449  * Concurrency: shouldn't matter.
2450  */
2451 static int osd_sync(const struct lu_env *env, struct dt_device *d)
2452 {
2453         int rc;
2454         struct super_block *s = osd_sb(osd_dt_dev(d));
2455         ENTRY;
2456
2457         down_read(&s->s_umount);
2458         rc = s->s_op->sync_fs(s, 1);
2459         up_read(&s->s_umount);
2460
2461         CDEBUG(D_CACHE, "%s: synced OSD: rc = %d\n", osd_dt_dev(d)->od_svname,
2462                rc);
2463
2464         return rc;
2465 }
2466
2467 /**
2468  * Start commit for OSD device.
2469  *
2470  * An implementation of dt_commit_async method for OSD device.
2471  * Asychronously starts underlayng fs sync and thereby a transaction
2472  * commit.
2473  *
2474  * \param env environment
2475  * \param d dt device
2476  *
2477  * \see dt_device_operations
2478  */
2479 static int osd_commit_async(const struct lu_env *env,
2480                             struct dt_device *d)
2481 {
2482         struct super_block *s = osd_sb(osd_dt_dev(d));
2483         int rc;
2484
2485         ENTRY;
2486
2487         CDEBUG(D_HA, "%s: async commit OSD\n", osd_dt_dev(d)->od_svname);
2488         down_read(&s->s_umount);
2489         rc = s->s_op->sync_fs(s, 0);
2490         up_read(&s->s_umount);
2491
2492         RETURN(rc);
2493 }
2494
2495 static int (*priv_security_file_alloc)(struct file *file);
2496
2497 int osd_security_file_alloc(struct file *file)
2498 {
2499         if (priv_security_file_alloc)
2500                 return priv_security_file_alloc(file);
2501         return 0;
2502 }
2503
2504 /*
2505  * Concurrency: shouldn't matter.
2506  */
2507 static int osd_ro(const struct lu_env *env, struct dt_device *d)
2508 {
2509         struct super_block *sb = osd_sb(osd_dt_dev(d));
2510         struct block_device *dev = sb->s_bdev;
2511         int rc = -EOPNOTSUPP;
2512
2513         ENTRY;
2514
2515         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
2516                osd_dt_dev(d)->od_svname, (long)dev, rc);
2517
2518         RETURN(rc);
2519 }
2520
2521 /**
2522  * Note: we do not count into QUOTA here.
2523  * If we mount with --data_journal we may need more.
2524  */
2525 const int osd_dto_credits_noquota[DTO_NR] = {
2526         /**
2527          * Insert.
2528          * INDEX_EXTRA_TRANS_BLOCKS(8) +
2529          * SINGLEDATA_TRANS_BLOCKS(8)
2530          * XXX Note: maybe iam need more, since iam have more level than
2531          *           EXT3 htree.
2532          */
2533         [DTO_INDEX_INSERT]  = 16,
2534         /**
2535          * Delete
2536          * just modify a single entry, probably merge few within a block
2537          */
2538         [DTO_INDEX_DELETE]  = 1,
2539         /**
2540          * Used for OI scrub
2541          */
2542         [DTO_INDEX_UPDATE]  = 16,
2543         /**
2544          * 4(inode, inode bits, groups, GDT)
2545          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
2546          */
2547         [DTO_OBJECT_CREATE] = 4,
2548         /**
2549          * 4(inode, inode bits, groups, GDT)
2550          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
2551          */
2552         [DTO_OBJECT_DELETE] = 4,
2553         /**
2554          * Attr set credits (inode)
2555          */
2556         [DTO_ATTR_SET_BASE] = 1,
2557         /**
2558          * Xattr set. The same as xattr of EXT3.
2559          * DATA_TRANS_BLOCKS(14)
2560          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
2561          * are also counted in. Do not know why?
2562          */
2563         [DTO_XATTR_SET]     = 14,
2564         /**
2565          * credits for inode change during write.
2566          */
2567         [DTO_WRITE_BASE]    = 3,
2568         /**
2569          * credits for single block write.
2570          */
2571         [DTO_WRITE_BLOCK]   = 14,
2572         /**
2573          * Attr set credits for chown.
2574          * This is extra credits for setattr, and it is null without quota
2575          */
2576         [DTO_ATTR_SET_CHOWN] = 0
2577 };
2578
2579 /* reserve or free quota for some operation */
2580 static int osd_reserve_or_free_quota(const struct lu_env *env,
2581                                      struct dt_device *dev,
2582                                      enum quota_type type, __u64 uid,
2583                                      __u64 gid, __s64 count, bool is_md)
2584 {
2585         int rc;
2586         struct osd_device       *osd = osd_dt_dev(dev);
2587         struct osd_thread_info  *info = osd_oti_get(env);
2588         struct lquota_id_info   *qi = &info->oti_qi;
2589         struct qsd_instance     *qsd = NULL;
2590
2591         ENTRY;
2592
2593         if (is_md)
2594                 qsd = osd->od_quota_slave_md;
2595         else
2596                 qsd = osd->od_quota_slave_dt;
2597
2598         rc = quota_reserve_or_free(env, qsd, qi, type, uid, gid, count, is_md);
2599         RETURN(rc);
2600 }
2601
2602 static const struct dt_device_operations osd_dt_ops = {
2603         .dt_root_get              = osd_root_get,
2604         .dt_statfs                = osd_statfs,
2605         .dt_trans_create          = osd_trans_create,
2606         .dt_trans_start           = osd_trans_start,
2607         .dt_trans_stop            = osd_trans_stop,
2608         .dt_trans_cb_add          = osd_trans_cb_add,
2609         .dt_conf_get              = osd_conf_get,
2610         .dt_mnt_sb_get            = osd_mnt_sb_get,
2611         .dt_sync                  = osd_sync,
2612         .dt_ro                    = osd_ro,
2613         .dt_commit_async          = osd_commit_async,
2614         .dt_reserve_or_free_quota = osd_reserve_or_free_quota,
2615 };
2616
2617 static void osd_read_lock(const struct lu_env *env, struct dt_object *dt,
2618                           unsigned int role)
2619 {
2620         struct osd_object *obj = osd_dt_obj(dt);
2621         struct osd_thread_info *oti = osd_oti_get(env);
2622
2623         LINVRNT(osd_invariant(obj));
2624
2625         LASSERT(obj->oo_owner != env);
2626         down_read_nested(&obj->oo_sem, role);
2627
2628         LASSERT(obj->oo_owner == NULL);
2629         oti->oti_r_locks++;
2630 }
2631
2632 static void osd_write_lock(const struct lu_env *env, struct dt_object *dt,
2633                            unsigned int role)
2634 {
2635         struct osd_object *obj = osd_dt_obj(dt);
2636         struct osd_thread_info *oti = osd_oti_get(env);
2637
2638         LINVRNT(osd_invariant(obj));
2639
2640         LASSERT(obj->oo_owner != env);
2641         down_write_nested(&obj->oo_sem, role);
2642
2643         LASSERT(obj->oo_owner == NULL);
2644         obj->oo_owner = env;
2645         oti->oti_w_locks++;
2646 }
2647
2648 static void osd_read_unlock(const struct lu_env *env, struct dt_object *dt)
2649 {
2650         struct osd_object *obj = osd_dt_obj(dt);
2651         struct osd_thread_info *oti = osd_oti_get(env);
2652
2653         LINVRNT(osd_invariant(obj));
2654
2655         LASSERT(oti->oti_r_locks > 0);
2656         oti->oti_r_locks--;
2657         up_read(&obj->oo_sem);
2658 }
2659
2660 static void osd_write_unlock(const struct lu_env *env, struct dt_object *dt)
2661 {
2662         struct osd_object *obj = osd_dt_obj(dt);
2663         struct osd_thread_info *oti = osd_oti_get(env);
2664
2665         LINVRNT(osd_invariant(obj));
2666
2667         LASSERT(obj->oo_owner == env);
2668         LASSERT(oti->oti_w_locks > 0);
2669         oti->oti_w_locks--;
2670         obj->oo_owner = NULL;
2671         up_write(&obj->oo_sem);
2672 }
2673
2674 static int osd_write_locked(const struct lu_env *env, struct dt_object *dt)
2675 {
2676         struct osd_object *obj = osd_dt_obj(dt);
2677
2678         LINVRNT(osd_invariant(obj));
2679
2680         return obj->oo_owner == env;
2681 }
2682
2683 static void osd_inode_getattr(const struct lu_env *env,
2684                               struct inode *inode, struct lu_attr *attr)
2685 {
2686         attr->la_valid  |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
2687                            LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
2688                            LA_PROJID | LA_FLAGS | LA_NLINK | LA_RDEV |
2689                            LA_BLKSIZE | LA_TYPE | LA_BTIME;
2690
2691         attr->la_atime = inode->i_atime.tv_sec;
2692         attr->la_mtime = inode->i_mtime.tv_sec;
2693         attr->la_ctime = inode->i_ctime.tv_sec;
2694         attr->la_btime = LDISKFS_I(inode)->i_crtime.tv_sec;
2695         attr->la_mode    = inode->i_mode;
2696         attr->la_size    = i_size_read(inode);
2697         attr->la_blocks  = inode->i_blocks;
2698         attr->la_uid     = i_uid_read(inode);
2699         attr->la_gid     = i_gid_read(inode);
2700         attr->la_projid  = i_projid_read(inode);
2701         attr->la_flags   = ll_inode_to_ext_flags(inode->i_flags);
2702         attr->la_nlink   = inode->i_nlink;
2703         attr->la_rdev    = inode->i_rdev;
2704         attr->la_blksize = 1 << inode->i_blkbits;
2705         attr->la_blkbits = inode->i_blkbits;
2706         /*
2707          * Ext4 did not transfer inherit flags from raw inode
2708          * to inode flags, and ext4 internally test raw inode
2709          * @i_flags directly. Instead of patching ext4, we do it here.
2710          */
2711         if (LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL)
2712                 attr->la_flags |= LUSTRE_PROJINHERIT_FL;
2713 }
2714
2715 static int osd_dirent_count(const struct lu_env *env, struct dt_object *dt,
2716                             u64 *count)
2717 {
2718         struct osd_object *obj = osd_dt_obj(dt);
2719         const struct dt_it_ops *iops;
2720         struct dt_it *it;
2721         int rc;
2722
2723         ENTRY;
2724
2725         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
2726         LASSERT(fid_is_namespace_visible(lu_object_fid(&obj->oo_dt.do_lu)));
2727
2728         if (obj->oo_dirent_count != LU_DIRENT_COUNT_UNSET) {
2729                 *count = obj->oo_dirent_count;
2730                 RETURN(0);
2731         }
2732
2733         /* directory not initialized yet */
2734         if (!dt->do_index_ops) {
2735                 *count = 0;
2736                 RETURN(0);
2737         }
2738
2739         iops = &dt->do_index_ops->dio_it;
2740         it = iops->init(env, dt, LUDA_64BITHASH);
2741         if (IS_ERR(it))
2742                 RETURN(PTR_ERR(it));
2743
2744         rc = iops->load(env, it, 0);
2745         if (rc < 0) {
2746                 if (rc == -ENODATA) {
2747                         rc = 0;
2748                         *count = 0;
2749                 }
2750                 GOTO(out, rc);
2751         }
2752         if (rc > 0)
2753                 rc = iops->next(env, it);
2754
2755         for (*count = 0; rc == 0 || rc == -ESTALE; rc = iops->next(env, it)) {
2756                 if (rc == -ESTALE)
2757                         continue;
2758
2759                 if (iops->key_size(env, it) == 0)
2760                         continue;
2761
2762                 (*count)++;
2763         }
2764         if (rc == 1) {
2765                 obj->oo_dirent_count = *count;
2766                 rc = 0;
2767         }
2768 out:
2769         iops->put(env, it);
2770         iops->fini(env, it);
2771
2772         RETURN(rc);
2773 }
2774
2775 static int osd_attr_get(const struct lu_env *env, struct dt_object *dt,
2776                         struct lu_attr *attr)
2777 {
2778         struct osd_object *obj = osd_dt_obj(dt);
2779         int rc = 0;
2780
2781         if (unlikely(!dt_object_exists(dt)))
2782                 return -ENOENT;
2783         if (unlikely(obj->oo_destroyed))
2784                 return -ENOENT;
2785
2786         LASSERT(!dt_object_remote(dt));
2787         LINVRNT(osd_invariant(obj));
2788
2789         spin_lock(&obj->oo_guard);
2790         osd_inode_getattr(env, obj->oo_inode, attr);
2791         if (obj->oo_lma_flags & LUSTRE_ORPHAN_FL) {
2792                 attr->la_valid |= LA_FLAGS;
2793                 attr->la_flags |= LUSTRE_ORPHAN_FL;
2794         }
2795         if (obj->oo_lma_flags & LUSTRE_ENCRYPT_FL) {
2796                 attr->la_valid |= LA_FLAGS;
2797                 attr->la_flags |= LUSTRE_ENCRYPT_FL;
2798         }
2799         spin_unlock(&obj->oo_guard);
2800
2801         if (S_ISDIR(obj->oo_inode->i_mode) &&
2802             fid_is_namespace_visible(lu_object_fid(&dt->do_lu)))
2803                 rc = osd_dirent_count(env, dt, &attr->la_dirent_count);
2804
2805         return rc;
2806 }
2807
2808 static int osd_declare_attr_qid(const struct lu_env *env,
2809                                 struct osd_object *obj,
2810                                 struct osd_thandle *oh, long long bspace,
2811                                 qid_t old_id, qid_t new_id, bool enforce,
2812                                 unsigned int type)
2813 {
2814         int rc;
2815         struct osd_thread_info *info = osd_oti_get(env);
2816         struct lquota_id_info  *qi = &info->oti_qi;
2817
2818         qi->lqi_type = type;
2819         /* inode accounting */
2820         qi->lqi_is_blk = false;
2821
2822         /* one more inode for the new id ... */
2823         qi->lqi_id.qid_uid = new_id;
2824         qi->lqi_space      = 1;
2825         /* Reserve credits for the new id */
2826         rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
2827         if (rc == -EDQUOT || rc == -EINPROGRESS)
2828                 rc = 0;
2829         if (rc)
2830                 RETURN(rc);
2831
2832         /* and one less inode for the current id */
2833         qi->lqi_id.qid_uid = old_id;
2834         qi->lqi_space = -1;
2835         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2836         if (rc == -EDQUOT || rc == -EINPROGRESS)
2837                 rc = 0;
2838         if (rc)
2839                 RETURN(rc);
2840
2841         /* block accounting */
2842         qi->lqi_is_blk = true;
2843
2844         /* more blocks for the new id ... */
2845         qi->lqi_id.qid_uid = new_id;
2846         qi->lqi_space      = bspace;
2847         /*
2848          * Credits for the new uid has been reserved, re-use "obj"
2849          * to save credit reservation.
2850          */
2851         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2852         if (rc == -EDQUOT || rc == -EINPROGRESS)
2853                 rc = 0;
2854         if (rc)
2855                 RETURN(rc);
2856
2857         /* and finally less blocks for the current uid */
2858         qi->lqi_id.qid_uid = old_id;
2859         qi->lqi_space      = -bspace;
2860         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2861         if (rc == -EDQUOT || rc == -EINPROGRESS)
2862                 rc = 0;
2863
2864         RETURN(rc);
2865 }
2866
2867 static int osd_declare_attr_set(const struct lu_env *env,
2868                                 struct dt_object *dt,
2869                                 const struct lu_attr *attr,
2870                                 struct thandle *handle)
2871 {
2872         struct osd_thandle *oh;
2873         struct osd_object *obj;
2874         qid_t uid;
2875         qid_t gid;
2876         long long bspace;
2877         int rc = 0;
2878         bool enforce;
2879
2880         ENTRY;
2881
2882         LASSERT(dt != NULL);
2883         LASSERT(handle != NULL);
2884
2885         obj = osd_dt_obj(dt);
2886         LASSERT(osd_invariant(obj));
2887
2888         oh = container_of(handle, struct osd_thandle, ot_super);
2889         LASSERT(oh->ot_handle == NULL);
2890
2891         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
2892                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2893
2894         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2895                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2896
2897         if (attr == NULL || obj->oo_inode == NULL)
2898                 RETURN(rc);
2899
2900         bspace   = obj->oo_inode->i_blocks << 9;
2901         bspace   = toqb(bspace);
2902
2903         /*
2904          * Changing ownership is always preformed by super user, it should not
2905          * fail with EDQUOT unless required explicitly.
2906          *
2907          * We still need to call the osd_declare_qid() to calculate the journal
2908          * credits for updating quota accounting files and to trigger quota
2909          * space adjustment once the operation is completed.
2910          */
2911         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
2912                 /* USERQUOTA */
2913                 uid = i_uid_read(obj->oo_inode);
2914                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
2915                 rc = osd_declare_attr_qid(env, obj, oh, bspace, uid,
2916                                           attr->la_uid, enforce, USRQUOTA);
2917                 if (rc)
2918                         RETURN(rc);
2919
2920                 gid = i_gid_read(obj->oo_inode);
2921                 CDEBUG(D_QUOTA, "declare uid %d -> %d gid %d -> %d\n", uid,
2922                        attr->la_uid, gid, attr->la_gid);
2923                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
2924                 rc = osd_declare_attr_qid(env, obj, oh, bspace, gid,
2925                                           attr->la_gid, enforce, GRPQUOTA);
2926                 if (rc)
2927                         RETURN(rc);
2928
2929         }
2930 #ifdef HAVE_PROJECT_QUOTA
2931         if (attr->la_valid & LA_PROJID) {
2932                 __u32 projid = i_projid_read(obj->oo_inode);
2933
2934                 enforce = (attr->la_valid & LA_PROJID) &&
2935                                         (attr->la_projid != projid);
2936                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2937                                           (qid_t)projid, (qid_t)attr->la_projid,
2938                                           enforce, PRJQUOTA);
2939                 if (rc)
2940                         RETURN(rc);
2941         }
2942 #endif
2943         RETURN(rc);
2944 }
2945
2946 static int osd_inode_setattr(const struct lu_env *env,
2947                              struct inode *inode, const struct lu_attr *attr)
2948 {
2949         __u64 bits = attr->la_valid;
2950
2951         /* Only allow set size for regular file */
2952         if (!S_ISREG(inode->i_mode))
2953                 bits &= ~(LA_SIZE | LA_BLOCKS);
2954
2955         if (bits == 0)
2956                 return 0;
2957
2958         if (bits & LA_ATIME)
2959                 inode->i_atime = osd_inode_time(inode, attr->la_atime);
2960         if (bits & LA_CTIME)
2961                 inode->i_ctime = osd_inode_time(inode, attr->la_ctime);
2962         if (bits & LA_MTIME)
2963                 inode->i_mtime = osd_inode_time(inode, attr->la_mtime);
2964         if (bits & LA_SIZE) {
2965                 spin_lock(&inode->i_lock);
2966                 LDISKFS_I(inode)->i_disksize = attr->la_size;
2967                 i_size_write(inode, attr->la_size);
2968                 spin_unlock(&inode->i_lock);
2969         }
2970
2971         /*
2972          * OSD should not change "i_blocks" which is used by quota.
2973          * "i_blocks" should be changed by ldiskfs only.
2974          */
2975         if (bits & LA_MODE)
2976                 inode->i_mode = (inode->i_mode & S_IFMT) |
2977                                 (attr->la_mode & ~S_IFMT);
2978         if (bits & LA_UID)
2979                 i_uid_write(inode, attr->la_uid);
2980         if (bits & LA_GID)
2981                 i_gid_write(inode, attr->la_gid);
2982         if (bits & LA_PROJID)
2983                 i_projid_write(inode, attr->la_projid);
2984         if (bits & LA_NLINK)
2985                 set_nlink(inode, attr->la_nlink);
2986         if (bits & LA_RDEV)
2987                 inode->i_rdev = attr->la_rdev;
2988
2989         if (bits & LA_FLAGS) {
2990                 /* always keep S_NOCMTIME */
2991                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
2992                                  S_NOCMTIME;
2993 #if defined(S_ENCRYPTED)
2994                 /* Always remove S_ENCRYPTED, because ldiskfs must not be
2995                  * aware of encryption status. It is just stored into LMA
2996                  * so that it can be forwared to client side.
2997                  */
2998                 inode->i_flags &= ~S_ENCRYPTED;
2999 #endif
3000                 /*
3001                  * Ext4 did not transfer inherit flags from
3002                  * @inode->i_flags to raw inode i_flags when writing
3003                  * flags, we do it explictly here.
3004                  */
3005                 if (attr->la_flags & LUSTRE_PROJINHERIT_FL)
3006                         LDISKFS_I(inode)->i_flags |= LUSTRE_PROJINHERIT_FL;
3007                 else
3008                         LDISKFS_I(inode)->i_flags &= ~LUSTRE_PROJINHERIT_FL;
3009         }
3010         return 0;
3011 }
3012
3013 #ifdef HAVE_PROJECT_QUOTA
3014 static int osd_transfer_project(struct inode *inode, __u32 projid,
3015                                 struct thandle *handle)
3016 {
3017         struct super_block *sb = inode->i_sb;
3018         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
3019         int err;
3020         kprojid_t kprojid;
3021         struct ldiskfs_iloc iloc;
3022         struct ldiskfs_inode *raw_inode;
3023         struct dquot *transfer_to[LDISKFS_MAXQUOTAS] = { };
3024
3025         if (!ldiskfs_has_feature_project(sb)) {
3026                 LASSERT(__kprojid_val(LDISKFS_I(inode)->i_projid)
3027                         == LDISKFS_DEF_PROJID);
3028                 if (projid != LDISKFS_DEF_PROJID)
3029                         return -EOPNOTSUPP;
3030                 else
3031                         return 0;
3032         }
3033
3034         if (LDISKFS_INODE_SIZE(sb) <= LDISKFS_GOOD_OLD_INODE_SIZE)
3035                 return -EOPNOTSUPP;
3036
3037         kprojid = make_kprojid(&init_user_ns, (projid_t)projid);
3038         if (projid_eq(kprojid, LDISKFS_I(inode)->i_projid))
3039                 return 0;
3040
3041         err = ldiskfs_get_inode_loc(inode, &iloc);
3042         if (err)
3043                 return err;
3044
3045         raw_inode = ldiskfs_raw_inode(&iloc);
3046         if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3047                 struct osd_thandle *oh = container_of(handle,
3048                                                       struct osd_thandle,
3049                                                       ot_super);
3050                 /**
3051                  * try to expand inode size automatically.
3052                  */
3053                 ldiskfs_mark_inode_dirty(oh->ot_handle, inode);
3054                 if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3055                         err = -EOVERFLOW;
3056                         brelse(iloc.bh);
3057                         return err;
3058                 }
3059         }
3060         brelse(iloc.bh);
3061
3062         dquot_initialize(inode);
3063         transfer_to[PRJQUOTA] = dqget(sb, make_kqid_projid(kprojid));
3064         if (transfer_to[PRJQUOTA]) {
3065                 lock_dquot_transfer(inode);
3066                 err = __dquot_transfer(inode, transfer_to);
3067                 unlock_dquot_transfer(inode);
3068                 dqput(transfer_to[PRJQUOTA]);
3069                 if (err)
3070                         return err;
3071         }
3072
3073         return err;
3074 }
3075 #endif
3076
3077 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr,
3078                               struct thandle *handle)
3079 {
3080         int rc;
3081
3082         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
3083             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
3084                 struct iattr iattr;
3085
3086                 CDEBUG(D_QUOTA,
3087                        "executing dquot_transfer inode %ld uid %d -> %d gid %d -> %d\n",
3088                        inode->i_ino, i_uid_read(inode), attr->la_uid,
3089                        i_gid_read(inode), attr->la_gid);
3090
3091                 dquot_initialize(inode);
3092                 iattr.ia_valid = 0;
3093                 if (attr->la_valid & LA_UID)
3094                         iattr.ia_valid |= ATTR_UID;
3095                 if (attr->la_valid & LA_GID)
3096                         iattr.ia_valid |= ATTR_GID;
3097                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3098                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3099
3100                 lock_dquot_transfer(inode);
3101                 rc = dquot_transfer(inode, &iattr);
3102                 unlock_dquot_transfer(inode);
3103                 if (rc) {
3104                         CERROR("%s: quota transfer failed. Is quota enforcement enabled on the ldiskfs filesystem? rc = %d\n",
3105                                osd_ino2name(inode), rc);
3106                         return rc;
3107                 }
3108         }
3109
3110         /* Handle project id transfer here properly */
3111         if (attr->la_valid & LA_PROJID &&
3112             attr->la_projid != i_projid_read(inode)) {
3113                 if (!projid_valid(make_kprojid(&init_user_ns, attr->la_projid)))
3114                         return -EINVAL;
3115 #ifdef HAVE_PROJECT_QUOTA
3116                 rc = osd_transfer_project(inode, attr->la_projid, handle);
3117 #else
3118                 rc = -ENOTSUPP;
3119 #endif
3120                 if (rc) {
3121                         CERROR("%s: quota transfer failed. Is project enforcement enabled on the ldiskfs filesystem? rc = %d\n",
3122                                osd_ino2name(inode), rc);
3123                         return rc;
3124                 }
3125         }
3126         return 0;
3127 }
3128
3129 static int osd_attr_set(const struct lu_env *env,
3130                         struct dt_object *dt,
3131                         const struct lu_attr *attr,
3132                         struct thandle *handle)
3133 {
3134         struct osd_object *obj = osd_dt_obj(dt);
3135         struct inode *inode;
3136         int rc;
3137
3138         if (!dt_object_exists(dt))
3139                 return -ENOENT;
3140
3141         LASSERT(handle != NULL);
3142         LASSERT(!dt_object_remote(dt));
3143         LASSERT(osd_invariant(obj));
3144
3145         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
3146
3147         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING) &&
3148             !osd_obj2dev(obj)->od_is_ost) {
3149                 struct osd_thread_info *oti = osd_oti_get(env);
3150                 const struct lu_fid *fid0 = lu_object_fid(&dt->do_lu);
3151                 struct lu_fid *fid1 = &oti->oti_fid;
3152                 struct osd_inode_id *id = &oti->oti_id;
3153                 struct iam_path_descr *ipd;
3154                 struct iam_container *bag;
3155                 struct osd_thandle *oh;
3156                 int rc;
3157
3158                 fid_cpu_to_be(fid1, fid0);
3159                 memset(id, 1, sizeof(*id));
3160                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
3161                                   fid0)->oi_dir.od_container;
3162                 ipd = osd_idx_ipd_get(env, bag);
3163                 if (unlikely(ipd == NULL))
3164                         RETURN(-ENOMEM);
3165
3166                 oh = container_of(handle, struct osd_thandle, ot_super);
3167                 rc = iam_update(oh->ot_handle, bag,
3168                                 (const struct iam_key *)fid1,
3169                                 (const struct iam_rec *)id, ipd);
3170                 osd_ipd_put(env, bag, ipd);
3171                 return(rc > 0 ? 0 : rc);
3172         }
3173
3174         inode = obj->oo_inode;
3175
3176         rc = osd_quota_transfer(inode, attr, handle);
3177         if (rc)
3178                 return rc;
3179
3180         spin_lock(&obj->oo_guard);
3181         rc = osd_inode_setattr(env, inode, attr);
3182         spin_unlock(&obj->oo_guard);
3183         if (rc != 0)
3184                 GOTO(out, rc);
3185
3186         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3187
3188         osd_trans_exec_check(env, handle, OSD_OT_ATTR_SET);
3189
3190         if (!(attr->la_valid & LA_FLAGS))
3191                 GOTO(out, rc);
3192
3193         /* Let's check if there are extra flags need to be set into LMA */
3194         if (attr->la_flags & LUSTRE_LMA_FL_MASKS) {
3195                 struct osd_thread_info *info = osd_oti_get(env);
3196                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
3197
3198                 LASSERT(!obj->oo_pfid_in_lma);
3199
3200                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
3201                                  &info->oti_ost_attrs);
3202                 if (rc)
3203                         GOTO(out, rc);
3204
3205                 lma->lma_incompat |=
3206                         lustre_to_lma_flags(attr->la_flags);
3207                 lustre_lma_swab(lma);
3208
3209                 osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3210
3211                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA,
3212                                      lma, sizeof(*lma), XATTR_REPLACE);
3213                 if (rc != 0) {
3214                         struct osd_device *osd = osd_obj2dev(obj);
3215
3216                         CWARN("%s: set "DFID" lma flags %u failed: rc = %d\n",
3217                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
3218                               lma->lma_incompat, rc);
3219                 } else {
3220                         obj->oo_lma_flags =
3221                                 attr->la_flags & LUSTRE_LMA_FL_MASKS;
3222                 }
3223                 osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
3224         }
3225 out:
3226
3227         return rc;
3228 }
3229
3230 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
3231                                            struct osd_object *obj,
3232                                            const char *name, const int namelen)
3233 {
3234         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
3235 }
3236
3237 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
3238                       umode_t mode, struct dt_allocation_hint *hint,
3239                       struct thandle *th, struct lu_attr *attr)
3240 {
3241         int result;
3242         struct osd_device *osd = osd_obj2dev(obj);
3243         struct osd_thandle *oth;
3244         struct dt_object *parent = NULL;
3245         struct inode *inode;
3246         struct iattr iattr = {
3247                 .ia_valid = ATTR_UID | ATTR_GID |
3248                             ATTR_CTIME | ATTR_MTIME | ATTR_ATIME,
3249                 .ia_ctime.tv_sec = attr->la_ctime,
3250                 .ia_mtime.tv_sec = attr->la_mtime,
3251                 .ia_atime.tv_sec = attr->la_atime,
3252                 .ia_uid = GLOBAL_ROOT_UID,
3253                 .ia_gid = GLOBAL_ROOT_GID,
3254         };
3255         const struct osd_timespec omit = { .tv_nsec = UTIME_OMIT };
3256
3257         if (attr->la_valid & LA_UID)
3258                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3259         if (attr->la_valid & LA_GID)
3260                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3261
3262         LINVRNT(osd_invariant(obj));
3263         LASSERT(obj->oo_inode == NULL);
3264         LASSERT(obj->oo_hl_head == NULL);
3265
3266         if (S_ISDIR(mode) && ldiskfs_pdo) {
3267                 obj->oo_hl_head =
3268                         ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
3269                 if (obj->oo_hl_head == NULL)
3270                         return -ENOMEM;
3271         }
3272
3273         oth = container_of(th, struct osd_thandle, ot_super);
3274         LASSERT(oth->ot_handle->h_transaction != NULL);
3275
3276         if (hint != NULL && hint->dah_parent != NULL &&
3277             !dt_object_remote(hint->dah_parent))
3278                 parent = hint->dah_parent;
3279
3280         /* if a time component is not valid set it to UTIME_OMIT */
3281         if (!(attr->la_valid & LA_CTIME))
3282                 iattr.ia_ctime = omit;
3283         if (!(attr->la_valid & LA_MTIME))
3284                 iattr.ia_mtime = omit;
3285         if (!(attr->la_valid & LA_ATIME))
3286                 iattr.ia_atime = omit;
3287
3288         inode = ldiskfs_create_inode(oth->ot_handle,
3289                                      parent ? osd_dt_obj(parent)->oo_inode :
3290                                               osd_sb(osd)->s_root->d_inode,
3291                                      mode, &iattr);
3292         if (!IS_ERR(inode)) {
3293                 /* Do not update file c/mtime in ldiskfs. */
3294                 inode->i_flags |= S_NOCMTIME;
3295
3296                 /*
3297                  * For new created object, it must be consistent,
3298                  * and it is unnecessary to scrub against it.
3299                  */
3300                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
3301
3302                 obj->oo_inode = inode;
3303                 result = 0;
3304         } else {
3305                 if (obj->oo_hl_head != NULL) {
3306                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
3307                         obj->oo_hl_head = NULL;
3308                 }
3309                 result = PTR_ERR(inode);
3310         }
3311         LINVRNT(osd_invariant(obj));
3312         return result;
3313 }
3314
3315 enum {
3316         OSD_NAME_LEN = 255
3317 };
3318
3319 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
3320                      struct lu_attr *attr,
3321                      struct dt_allocation_hint *hint,
3322                      struct dt_object_format *dof,
3323                      struct thandle *th)
3324 {
3325         int result;
3326         struct osd_thandle *oth;
3327         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX | S_ISGID));
3328
3329         LASSERT(S_ISDIR(attr->la_mode));
3330
3331         oth = container_of(th, struct osd_thandle, ot_super);
3332         LASSERT(oth->ot_handle->h_transaction != NULL);
3333         if (fid_is_namespace_visible(lu_object_fid(&obj->oo_dt.do_lu)))
3334                 obj->oo_dirent_count = 0;
3335         result = osd_mkfile(info, obj, mode, hint, th, attr);
3336
3337         return result;
3338 }
3339
3340 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
3341                         struct lu_attr *attr,
3342                         struct dt_allocation_hint *hint,
3343                         struct dt_object_format *dof,
3344                         struct thandle *th)
3345 {
3346         int result;
3347         struct osd_thandle *oth;
3348         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
3349
3350         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
3351
3352         LASSERT(S_ISREG(attr->la_mode));
3353
3354         oth = container_of(th, struct osd_thandle, ot_super);
3355         LASSERT(oth->ot_handle->h_transaction != NULL);
3356
3357         result = osd_mkfile(info, obj, mode, hint, th, attr);
3358         if (result == 0) {
3359                 LASSERT(obj->oo_inode != NULL);
3360                 if (feat->dif_flags & DT_IND_VARKEY)
3361                         result = iam_lvar_create(obj->oo_inode,
3362                                                  feat->dif_keysize_max,
3363                                                  feat->dif_ptrsize,
3364                                                  feat->dif_recsize_max,
3365                                                  oth->ot_handle);
3366                 else
3367                         result = iam_lfix_create(obj->oo_inode,
3368                                                  feat->dif_keysize_max,
3369                                                  feat->dif_ptrsize,
3370                                                  feat->dif_recsize_max,
3371                                                  oth->ot_handle);
3372         }
3373         return result;
3374 }
3375
3376 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
3377                      struct lu_attr *attr,
3378                      struct dt_allocation_hint *hint,
3379                      struct dt_object_format *dof,
3380                      struct thandle *th)
3381 {
3382         LASSERT(S_ISREG(attr->la_mode));
3383         return osd_mkfile(info, obj, (attr->la_mode &
3384                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3385                           attr);
3386 }
3387
3388 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
3389                      struct lu_attr *attr,
3390                      struct dt_allocation_hint *hint,
3391                      struct dt_object_format *dof,
3392                      struct thandle *th)
3393 {
3394         LASSERT(S_ISLNK(attr->la_mode));
3395         return osd_mkfile(info, obj, (attr->la_mode &
3396                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3397                           attr);
3398 }
3399
3400 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
3401                      struct lu_attr *attr,
3402                      struct dt_allocation_hint *hint,
3403                      struct dt_object_format *dof,
3404                      struct thandle *th)
3405 {
3406         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
3407         int result;
3408
3409         LINVRNT(osd_invariant(obj));
3410         LASSERT(obj->oo_inode == NULL);
3411         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
3412                 S_ISFIFO(mode) || S_ISSOCK(mode));
3413
3414         result = osd_mkfile(info, obj, mode, hint, th, attr);
3415         if (result == 0) {
3416                 LASSERT(obj->oo_inode != NULL);
3417                 /*
3418                  * This inode should be marked dirty for i_rdev.  Currently
3419                  * that is done in the osd_attr_init().
3420                  */
3421                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
3422                                    attr->la_rdev);
3423         }
3424         LINVRNT(osd_invariant(obj));
3425         return result;
3426 }
3427
3428 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
3429                               struct lu_attr *,
3430                               struct dt_allocation_hint *hint,
3431                               struct dt_object_format *dof,
3432                               struct thandle *);
3433
3434 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
3435 {
3436         osd_obj_type_f result;
3437
3438         switch (type) {
3439         case DFT_DIR:
3440                 result = osd_mkdir;
3441                 break;
3442         case DFT_REGULAR:
3443                 result = osd_mkreg;
3444                 break;
3445         case DFT_SYM:
3446                 result = osd_mksym;
3447                 break;
3448         case DFT_NODE:
3449                 result = osd_mknod;
3450                 break;
3451         case DFT_INDEX:
3452                 result = osd_mk_index;
3453                 break;
3454
3455         default:
3456                 LBUG();
3457                 break;
3458         }
3459         return result;
3460 }
3461
3462 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
3463                         struct dt_object *parent, struct dt_object *child,
3464                         umode_t child_mode)
3465 {
3466         LASSERT(ah);
3467
3468         ah->dah_parent = parent;
3469         ah->dah_mode = child_mode;
3470
3471         if (parent != NULL && !dt_object_remote(parent)) {
3472                 /* will help to find FID->ino at dt_insert("..") */
3473                 struct osd_object *pobj = osd_dt_obj(parent);
3474
3475                 osd_idc_find_and_init(env, osd_obj2dev(pobj), pobj);
3476         }
3477 }
3478
3479 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
3480                           struct lu_attr *attr, struct dt_object_format *dof,
3481                           struct thandle *handle)
3482 {
3483         struct inode *inode = obj->oo_inode;
3484         __u64 valid = attr->la_valid;
3485         int result;
3486
3487         attr->la_valid &= ~(LA_TYPE | LA_MODE);
3488
3489         if (dof->dof_type != DFT_NODE)
3490                 attr->la_valid &= ~LA_RDEV;
3491         if ((valid & LA_ATIME) && (attr->la_atime == inode->i_atime.tv_sec))
3492                 attr->la_valid &= ~LA_ATIME;
3493         if ((valid & LA_CTIME) && (attr->la_ctime == inode->i_ctime.tv_sec))
3494                 attr->la_valid &= ~LA_CTIME;
3495         if ((valid & LA_MTIME) && (attr->la_mtime == inode->i_mtime.tv_sec))
3496                 attr->la_valid &= ~LA_MTIME;
3497
3498         result = osd_quota_transfer(inode, attr, handle);
3499         if (result)
3500                 return;
3501
3502         if (attr->la_valid != 0) {
3503                 result = osd_inode_setattr(info->oti_env, inode, attr);
3504                 /*
3505                  * The osd_inode_setattr() should always succeed here.  The
3506                  * only error that could be returned is EDQUOT when we are
3507                  * trying to change the UID or GID of the inode. However, this
3508                  * should not happen since quota enforcement is no longer
3509                  * enabled on ldiskfs (lquota takes care of it).
3510                  */
3511                 LASSERTF(result == 0, "%d\n", result);
3512                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3513         }
3514
3515         attr->la_valid = valid;
3516 }
3517
3518 /**
3519  * Helper function for osd_create()
3520  *
3521  * \retval 0, on success
3522  */
3523 static int __osd_create(struct osd_thread_info *info, struct osd_object *obj,
3524                         struct lu_attr *attr, struct dt_allocation_hint *hint,
3525                         struct dt_object_format *dof, struct thandle *th)
3526 {
3527         int result;
3528         __u32 umask;
3529
3530         osd_trans_exec_op(info->oti_env, th, OSD_OT_CREATE);
3531
3532         /* we drop umask so that permissions we pass are not affected */
3533         umask = current->fs->umask;
3534         current->fs->umask = 0;
3535
3536         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
3537                                                   th);
3538         if (likely(obj->oo_inode != NULL)) {
3539                 LASSERT(obj->oo_inode->i_state & I_NEW);
3540
3541                 /*
3542                  * Unlock the inode before attr initialization to avoid
3543                  * unnecessary dqget operations. LU-6378
3544                  */
3545                 unlock_new_inode(obj->oo_inode);
3546         }
3547
3548         if (likely(result == 0)) {
3549                 osd_attr_init(info, obj, attr, dof, th);
3550                 osd_object_init0(obj);
3551         }
3552
3553         /* restore previous umask value */
3554         current->fs->umask = umask;
3555
3556         osd_trans_exec_check(info->oti_env, th, OSD_OT_CREATE);
3557
3558         return result;
3559 }
3560
3561 /**
3562  * Helper function for osd_create()
3563  *
3564  * \retval 0, on success
3565  */
3566 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
3567                            const struct lu_fid *fid, struct thandle *th)
3568 {
3569         struct osd_thread_info *info = osd_oti_get(env);
3570         struct osd_inode_id    *id   = &info->oti_id;
3571         struct osd_device      *osd  = osd_obj2dev(obj);
3572         struct osd_thandle     *oh;
3573         int rc;
3574
3575         LASSERT(obj->oo_inode != NULL);
3576
3577         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_OI_ENOSPC))
3578                 return -ENOSPC;
3579
3580         oh = container_of(th, struct osd_thandle, ot_super);
3581         LASSERT(oh->ot_handle);
3582         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3583
3584         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
3585         rc = osd_oi_insert(info, osd, fid, id, oh->ot_handle,
3586                            OI_CHECK_FLD, NULL);
3587         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP) && osd->od_is_ost) {
3588                 struct lu_fid next_fid = *fid;
3589
3590                 /* insert next object in advance, and map to the same inode */
3591                 next_fid.f_oid++;
3592                 if (next_fid.f_oid != 0) {
3593                         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3594                         osd_oi_insert(info, osd, &next_fid, id, oh->ot_handle,
3595                                       OI_CHECK_FLD, NULL);
3596                         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3597                 }
3598         }
3599
3600         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3601
3602         return rc;
3603 }
3604
3605 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
3606                    u64 seq, struct lu_seq_range *range)
3607 {
3608         struct seq_server_site *ss = osd_seq_site(osd);
3609
3610         if (fid_seq_is_idif(seq)) {
3611                 fld_range_set_ost(range);
3612                 range->lsr_index = idif_ost_idx(seq);
3613                 return 0;
3614         }
3615
3616         if (!fid_seq_in_fldb(seq)) {
3617                 fld_range_set_mdt(range);
3618                 if (ss != NULL)
3619                         /*
3620                          * FIXME: If ss is NULL, it suppose not get lsr_index
3621                          * at all
3622                          */
3623                         range->lsr_index = ss->ss_node_id;
3624                 return 0;
3625         }
3626
3627         LASSERT(ss != NULL);
3628         fld_range_set_any(range);
3629         /* OSD will only do local fld lookup */
3630         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
3631 }
3632
3633 static int osd_declare_create(const struct lu_env *env, struct dt_object *dt,
3634                               struct lu_attr *attr,
3635                               struct dt_allocation_hint *hint,
3636                               struct dt_object_format *dof,
3637                               struct thandle *handle)
3638 {
3639         struct osd_thandle *oh;
3640         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3641         int credits;
3642         int rc;
3643
3644         ENTRY;
3645
3646         LASSERT(handle != NULL);
3647
3648         oh = container_of(handle, struct osd_thandle, ot_super);
3649         LASSERT(oh->ot_handle == NULL);
3650
3651         /*
3652          * EA object consumes more credits than regular object: osd_mk_index
3653          * vs. osd_mkreg: osd_mk_index will create 2 blocks for root_node and
3654          * leaf_node, could involves the block, block bitmap, groups, GDT
3655          * change for each block, so add 4 * 2 credits in that case.
3656          *
3657          * The default ACL initialization may consume an additional 16 blocks
3658          */
3659         credits = osd_dto_credits_noquota[DTO_OBJECT_CREATE] +
3660                   ((dof->dof_type == DFT_INDEX) ? 4 * 2 : 0);
3661
3662         /**
3663          * While ldiskfs_new_inode() calls ldiskfs_init_acl() we have to add
3664          * credits for possible default ACL creation in new inode
3665          */
3666         if (hint && hint->dah_acl_len)
3667                 credits += osd_calc_bkmap_credits(sb, NULL, 0, -1,
3668                                 (hint->dah_acl_len + sb->s_blocksize - 1) >>
3669                                 sb->s_blocksize_bits);
3670
3671         osd_trans_declare_op(env, oh, OSD_OT_CREATE, credits);
3672
3673         /*
3674          * Reuse idle OI block may cause additional one OI block
3675          * to be changed.
3676          */
3677         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3678                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3679         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP))
3680                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3681                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3682
3683         /* will help to find FID->ino mapping at dt_insert() */
3684         rc = osd_idc_find_and_init(env, osd_obj2dev(osd_dt_obj(dt)),
3685                                    osd_dt_obj(dt));
3686         if (rc != 0)
3687                 RETURN(rc);
3688
3689         if (!attr)
3690                 RETURN(0);
3691
3692         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid,
3693                                    attr->la_projid, 1, oh, osd_dt_obj(dt),
3694                                    NULL, OSD_QID_INODE);
3695         if (rc != 0)
3696                 RETURN(rc);
3697
3698         RETURN(rc);
3699 }
3700
3701 /**
3702  * Called to destroy on-disk representation of the object
3703  *
3704  * Concurrency: must be locked
3705  */
3706 static int osd_declare_destroy(const struct lu_env *env, struct dt_object *dt,
3707                                struct thandle *th)
3708 {
3709         struct osd_object *obj = osd_dt_obj(dt);
3710         struct inode *inode = obj->oo_inode;
3711         struct osd_thandle *oh;
3712         int rc;
3713
3714         ENTRY;
3715
3716         if (inode == NULL)
3717                 RETURN(-ENOENT);
3718
3719         oh = container_of(th, struct osd_thandle, ot_super);
3720         LASSERT(oh->ot_handle == NULL);
3721
3722         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
3723                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
3724
3725         /* For removing agent entry */
3726         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu))
3727                 oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
3728
3729         /*
3730          * Recycle idle OI leaf may cause additional three OI blocks
3731          * to be changed.
3732          */
3733         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3734                 osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3735                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
3736         /* one less inode */
3737         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3738                                    i_projid_read(inode), -1, oh, obj, NULL,
3739                                    OSD_QID_INODE);
3740         if (rc)
3741                 RETURN(rc);
3742         /* data to be truncated */
3743         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3744                                    i_projid_read(inode), 0, oh, obj, NULL,
3745                                    OSD_QID_BLK);
3746         if (rc)
3747                 RETURN(rc);
3748
3749         /*
3750          * will help to find FID->ino when this object is being
3751          * added to PENDING
3752          */
3753         rc = osd_idc_find_and_init(env, osd_obj2dev(obj), obj);
3754
3755         RETURN(rc);
3756 }
3757
3758 static int osd_destroy(const struct lu_env *env, struct dt_object *dt,
3759                        struct thandle *th)
3760 {
3761         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3762         struct osd_object *obj = osd_dt_obj(dt);
3763         struct inode *inode = obj->oo_inode;
3764         struct osd_device *osd = osd_obj2dev(obj);
3765         struct osd_thandle *oh;
3766         int result;
3767
3768         ENTRY;
3769
3770         oh = container_of(th, struct osd_thandle, ot_super);
3771         LASSERT(oh->ot_handle);
3772         LASSERT(inode);
3773         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
3774
3775         if (unlikely(fid_is_acct(fid)))
3776                 RETURN(-EPERM);
3777
3778         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu)) {
3779                 result = osd_delete_from_remote_parent(env, osd, obj, oh, true);
3780                 if (result != 0)
3781                         CERROR("%s: remove agent entry "DFID": rc = %d\n",
3782                                osd_name(osd), PFID(fid), result);
3783         }
3784
3785         if (S_ISDIR(inode->i_mode)) {
3786                 if (inode->i_nlink > 2)
3787                         CERROR("%s: directory "DFID" ino %lu link count is %u at unlink. run e2fsck to repair\n",
3788                                osd_name(osd), PFID(fid), inode->i_ino,
3789                                inode->i_nlink);
3790
3791                 spin_lock(&obj->oo_guard);
3792                 clear_nlink(inode);
3793                 spin_unlock(&obj->oo_guard);
3794                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3795         }
3796
3797         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
3798
3799         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
3800
3801         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3802                 result = osd_oi_delete(osd_oti_get(env), osd, fid,
3803                                        oh->ot_handle, OI_CHECK_FLD);
3804
3805         osd_trans_exec_check(env, th, OSD_OT_DESTROY);
3806         /* XXX: add to ext3 orphan list */
3807         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
3808
3809         /* not needed in the cache anymore */
3810         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
3811         obj->oo_destroyed = 1;
3812
3813         RETURN(0);
3814 }
3815
3816 /**
3817  * Put the fid into lustre_mdt_attrs, and then place the structure
3818  * inode's ea. This fid should not be altered during the life time
3819  * of the inode.
3820  *
3821  * \retval +ve, on success
3822  * \retval -ve, on error
3823  *
3824  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
3825  */
3826 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
3827                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
3828 {
3829         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
3830         struct lustre_mdt_attrs *lma = &loa->loa_lma;
3831         int rc;
3832
3833         ENTRY;
3834
3835         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
3836                 RETURN(0);
3837
3838         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_OST_EA_FID_SET))
3839                 rc = -ENOMEM;
3840
3841         lustre_loa_init(loa, fid, compat, incompat);
3842         lustre_loa_swab(loa, false);
3843
3844         /*
3845          * For the OST device with 256 bytes inode size by default,
3846          * the PFID EA will be stored together with LMA EA to avoid
3847          * performance trouble. Otherwise the PFID EA can be stored
3848          * independently. LU-8998
3849          */
3850         if ((compat & LMAC_FID_ON_OST) &&
3851             LDISKFS_INODE_SIZE(inode->i_sb) <= 256)
3852                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3853                                      sizeof(*loa), XATTR_CREATE);
3854         else
3855                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3856                                      sizeof(*lma), XATTR_CREATE);
3857         /*
3858          * LMA may already exist, but we need to check that all the
3859          * desired compat/incompat flags have been added.
3860          */
3861         if (unlikely(rc == -EEXIST)) {
3862                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
3863                                      XATTR_NAME_LMA, (void *)loa, sizeof(*loa));
3864                 if (rc < 0)
3865                         RETURN(rc);
3866
3867                 if (rc < sizeof(*lma))
3868                         RETURN(-EINVAL);
3869
3870                 lustre_loa_swab(loa, true);
3871                 if (lu_fid_eq(fid, &lma->lma_self_fid) &&
3872                     ((compat == 0 && incompat == 0) ||
3873                      (!(~lma->lma_compat & compat) &&
3874                       !(~lma->lma_incompat & incompat))))
3875                         RETURN(0);
3876
3877                 lma->lma_self_fid = *fid;
3878                 lma->lma_compat |= compat;
3879                 lma->lma_incompat |= incompat;
3880                 if (rc == sizeof(*lma)) {
3881                         lustre_lma_swab(lma);
3882                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3883                                              sizeof(*lma), XATTR_REPLACE);
3884                 } else {
3885                         lustre_loa_swab(loa, false);
3886                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3887                                              sizeof(*loa), XATTR_REPLACE);
3888                 }
3889         }
3890
3891         RETURN(rc);
3892 }
3893
3894 /**
3895  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
3896  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
3897  * To have compatilibility with 1.8 ldiskfs driver we need to have
3898  * magic number at start of fid data.
3899  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
3900  * its inmemory API.
3901  */
3902 static void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
3903                                          const struct lu_fid *fid)
3904 {
3905         if (!fid_is_namespace_visible(fid) ||
3906             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
3907                 param->edp_magic = 0;
3908                 return;
3909         }
3910
3911         param->edp_magic = LDISKFS_LUFID_MAGIC;
3912         param->edp_len =  sizeof(struct lu_fid) + 1;
3913         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
3914 }
3915
3916 /**
3917  * Try to read the fid from inode ea into dt_rec.
3918  *
3919  * \param fid object fid.
3920  *
3921  * \retval 0 on success
3922  */
3923 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
3924                           __u32 ino, struct lu_fid *fid,
3925                           struct osd_inode_id *id)
3926 {
3927         struct osd_thread_info *info  = osd_oti_get(env);
3928         struct inode *inode;
3929
3930         ENTRY;
3931
3932         osd_id_gen(id, ino, OSD_OII_NOGEN);
3933         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
3934         if (IS_ERR(inode))
3935                 RETURN(PTR_ERR(inode));
3936
3937         iput(inode);
3938         RETURN(0);
3939 }
3940
3941 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
3942                                         struct inode *dir,
3943                                         struct inode *parent_dir,
3944                                         const struct lu_fid *dot_fid,
3945                                         const struct lu_fid *dot_dot_fid,
3946                                         struct osd_thandle *oth)
3947 {
3948         struct ldiskfs_dentry_param *dot_ldp;
3949         struct ldiskfs_dentry_param *dot_dot_ldp;
3950         __u32 saved_nlink = dir->i_nlink;
3951         int rc;
3952
3953         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_DOTDOT_ENOSPC))
3954                 return -ENOSPC;
3955
3956         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
3957         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
3958
3959         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3960         dot_ldp->edp_magic = 0;
3961
3962         rc = ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
3963                                     dir, dot_ldp, dot_dot_ldp);
3964         /*
3965          * The ldiskfs_add_dot_dotdot() may dir->i_nlink as 2, then
3966          * the subseqent ref_add() will increase the dir->i_nlink
3967          * as 3. That is incorrect for new created directory.
3968          *
3969          * It looks like hack, because we want to make the OSD API
3970          * to be order-independent for new created directory object
3971          * between dt_insert(..) and ref_add() operations.
3972          *
3973          * Here, we only restore the in-RAM dir-inode's nlink attr,
3974          * becuase if the nlink attr is not 2, then there will be
3975          * ref_add() called following the dt_insert(..), such call
3976          * will make both the in-RAM and on-disk dir-inode's nlink
3977          * attr to be set as 2. LU-7447
3978          */
3979         set_nlink(dir, saved_nlink);
3980         return rc;
3981 }
3982
3983 /**
3984  * Create an local agent inode for remote entry
3985  */
3986 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
3987                                                   struct osd_device *osd,
3988                                                   struct osd_object *pobj,
3989                                                   const struct lu_fid *fid,
3990                                                   __u32 type,
3991                                                   struct thandle *th)
3992 {
3993         struct osd_thread_info *info = osd_oti_get(env);
3994         struct inode *local;
3995         struct osd_thandle *oh;
3996         struct iattr iattr = {
3997                 .ia_valid = ATTR_UID | ATTR_GID |
3998                             ATTR_CTIME | ATTR_MTIME | ATTR_ATIME,
3999                 .ia_ctime.tv_nsec = UTIME_OMIT,
4000                 .ia_mtime.tv_nsec = UTIME_OMIT,
4001                 .ia_atime.tv_nsec = UTIME_OMIT,
4002                 .ia_uid = GLOBAL_ROOT_UID,
4003                 .ia_gid = GLOBAL_ROOT_GID,
4004         };
4005         int rc;
4006
4007         ENTRY;
4008
4009         LASSERT(th);
4010         oh = container_of(th, struct osd_thandle, ot_super);
4011         LASSERT(oh->ot_handle->h_transaction != NULL);
4012
4013         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode,
4014                                      type, &iattr);
4015         if (IS_ERR(local)) {
4016                 CERROR("%s: create local error %d\n", osd_name(osd),
4017                        (int)PTR_ERR(local));
4018                 RETURN(local);
4019         }
4020
4021         /*
4022          * restore i_gid in case S_ISGID is set, we will inherit S_ISGID and set
4023          * correct gid on remote file, not agent here
4024          */
4025         local->i_gid = current_fsgid();
4026         ldiskfs_set_inode_state(local, LDISKFS_STATE_LUSTRE_NOSCRUB);
4027
4028         /* e2fsck doesn't like empty symlinks.  Store remote FID as symlink.
4029          * That gives e2fsck something to look at and be happy, and allows
4030          * debugging if we need to determine where this symlink came from.
4031          */
4032         if (S_ISLNK(type)) {
4033                 BUILD_BUG_ON(LDISKFS_N_BLOCKS * 4 < FID_LEN + 1);
4034                 rc = scnprintf((char *)LDISKFS_I(local)->i_data,
4035                                LDISKFS_N_BLOCKS * 4, DFID, PFID(fid));
4036
4037                 i_size_write(local, rc);
4038                 LDISKFS_I(local)->i_disksize = rc;
4039         }
4040         unlock_new_inode(local);
4041
4042         /* Agent inode should not have project ID */
4043 #ifdef  HAVE_PROJECT_QUOTA
4044         if (LDISKFS_I(pobj->oo_inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
4045             i_projid_read(pobj->oo_inode) != 0) {
4046                 rc = osd_transfer_project(local, 0, th);
4047                 if (rc) {
4048                         CERROR("%s: quota transfer failed:. Is project quota enforcement enabled on the ldiskfs filesystem? rc = %d\n",
4049                                osd_ino2name(local), rc);
4050                         RETURN(ERR_PTR(rc));
4051                 }
4052         }
4053 #endif
4054         /* Set special LMA flag for local agent inode */
4055         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
4056         if (rc != 0) {
4057                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
4058                        osd_name(osd), PFID(fid), rc);
4059                 RETURN(ERR_PTR(rc));
4060         }
4061
4062         if (!S_ISDIR(type))
4063                 RETURN(local);
4064
4065         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
4066                                          lu_object_fid(&pobj->oo_dt.do_lu),
4067                                          fid, oh);
4068         if (rc != 0) {
4069                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
4070                         osd_name(osd), PFID(fid), rc);
4071                 RETURN(ERR_PTR(rc));
4072         }
4073
4074         RETURN(local);
4075 }
4076
4077 /**
4078  * when direntry is deleted, we have to take care of possible agent inode
4079  * referenced by that. unfortunately we can't do this at that point:
4080  * iget() within a running transaction leads to deadlock and we better do
4081  * not call that every delete declaration to save performance. so we put
4082  * a potention agent inode on a list and process that once the transaction
4083  * is over. Notice it's not any worse in terms of real orphans as regular
4084  * object destroy doesn't put inodes on the on-disk orphan list. this should
4085  * be addressed separately
4086  */
4087 static int osd_schedule_agent_inode_removal(const struct lu_env *env,
4088                                             struct osd_thandle *oh,
4089                                             __u32 ino)
4090 {
4091         struct osd_device *osd = osd_dt_dev(oh->ot_super.th_dev);
4092         struct osd_obj_orphan *oor;
4093
4094         OBD_ALLOC_PTR(oor);
4095         if (oor == NULL)
4096                 return -ENOMEM;
4097
4098         oor->oor_ino = ino;
4099         oor->oor_env = (struct lu_env *)env;
4100         spin_lock(&osd->od_osfs_lock);
4101         list_add(&oor->oor_list, &osd->od_orphan_list);
4102         spin_unlock(&osd->od_osfs_lock);
4103
4104         oh->ot_remove_agents = 1;
4105
4106         return 0;
4107
4108 }
4109
4110 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
4111                                                 struct osd_device *osd)
4112 {
4113         struct osd_thread_info *info = osd_oti_get(env);
4114         struct osd_obj_orphan *oor, *tmp;
4115         struct osd_inode_id id;
4116         LIST_HEAD(list);
4117         struct inode *inode;
4118         struct lu_fid fid;
4119         handle_t *jh;
4120         __u32 ino;
4121
4122         spin_lock(&osd->od_osfs_lock);
4123         list_for_each_entry_safe(oor, tmp, &osd->od_orphan_list, oor_list) {
4124                 if (oor->oor_env == env)
4125                         list_move(&oor->oor_list, &list);
4126         }
4127         spin_unlock(&osd->od_osfs_lock);
4128
4129         list_for_each_entry_safe(oor, tmp, &list, oor_list) {
4130
4131                 ino = oor->oor_ino;
4132
4133                 list_del(&oor->oor_list);
4134                 OBD_FREE_PTR(oor);
4135
4136                 osd_id_gen(&id, ino, OSD_OII_NOGEN);
4137                 inode = osd_iget_fid(info, osd, &id, &fid);
4138                 if (IS_ERR(inode))
4139                         continue;
4140
4141                 if (!osd_remote_fid(env, osd, &fid)) {
4142                         iput(inode);
4143                         continue;
4144                 }
4145
4146                 jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC, 1);
4147                 clear_nlink(inode);
4148                 mark_inode_dirty(inode);
4149                 ldiskfs_journal_stop(jh);
4150                 iput(inode);
4151         }
4152
4153         return 0;
4154 }
4155
4156 /**
4157  * OSD layer object create function for OST objects (b=11826).
4158  *
4159  * The FID is inserted into inode xattr here.
4160  *
4161  * \retval   0, on success
4162  * \retval -ve, on error
4163  */
4164 static int osd_create(const struct lu_env *env, struct dt_object *dt,
4165                       struct lu_attr *attr, struct dt_allocation_hint *hint,
4166                       struct dt_object_format *dof, struct thandle *th)
4167 {
4168         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4169         struct osd_object *obj = osd_dt_obj(dt);
4170         struct osd_thread_info *info = osd_oti_get(env);
4171         int result, on_ost = 0;
4172
4173         ENTRY;
4174
4175         if (dt_object_exists(dt))
4176                 RETURN(-EEXIST);
4177
4178         LINVRNT(osd_invariant(obj));
4179         LASSERT(!dt_object_remote(dt));
4180         LASSERT(osd_is_write_locked(env, obj));
4181         LASSERT(th != NULL);
4182
4183         if (unlikely(fid_is_acct(fid)))
4184                 /*
4185                  * Quota files can't be created from the kernel any more,
4186                  * 'tune2fs -O quota' will take care of creating them
4187                  */
4188                 RETURN(-EPERM);
4189
4190         result = __osd_create(info, obj, attr, hint, dof, th);
4191         if (result == 0) {
4192                 if (fid_is_idif(fid) &&
4193                     !osd_dev(dt->do_lu.lo_dev)->od_index_in_idif) {
4194                         struct lu_fid *tfid = &info->oti_fid;
4195                         struct ost_id *oi   = &info->oti_ostid;
4196
4197                         fid_to_ostid(fid, oi);
4198                         ostid_to_fid(tfid, oi, 0);
4199                         on_ost = 1;
4200                         result = osd_ea_fid_set(info, obj->oo_inode, tfid,
4201                                                 LMAC_FID_ON_OST, 0);
4202                 } else {
4203                         on_ost = fid_is_on_ost(info, osd_obj2dev(obj),
4204                                                fid, OI_CHECK_FLD);
4205                         result = osd_ea_fid_set(info, obj->oo_inode, fid,
4206                                                 on_ost ? LMAC_FID_ON_OST : 0,
4207                                                 0);
4208                 }
4209                 if (obj->oo_dt.do_body_ops == &osd_body_ops_new)
4210                         obj->oo_dt.do_body_ops = &osd_body_ops;
4211         }
4212
4213         if (!result && !CFS_FAIL_CHECK(OBD_FAIL_OSD_NO_OI_ENTRY)) {
4214                 struct inode *inode = obj->oo_inode;
4215
4216                 result = __osd_oi_insert(env, obj, fid, th);
4217                 if (result && inode) {
4218                         spin_lock(&obj->oo_guard);
4219                         clear_nlink(inode);
4220                         spin_unlock(&obj->oo_guard);
4221                         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4222                         ldiskfs_set_inode_state(inode,
4223                                                 LDISKFS_STATE_LUSTRE_DESTROY);
4224                         iput(inode);
4225                         obj->oo_inode = NULL;
4226                 }
4227         }
4228
4229         /*
4230          * a small optimization - dt_insert() isn't usually applied
4231          * to OST objects, so we don't need to cache OI mapping for
4232          * OST objects
4233          */
4234         if (result == 0 && on_ost == 0) {
4235                 struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4236
4237                 result = osd_idc_find_and_init(env, osd, obj);
4238                 LASSERT(result == 0);
4239         }
4240
4241         LASSERT(ergo(result == 0,
4242                      dt_object_exists(dt) && !dt_object_remote(dt)));
4243         LINVRNT(osd_invariant(obj));
4244         RETURN(result);
4245 }
4246
4247 static int osd_declare_ref_add(const struct lu_env *env, struct dt_object *dt,
4248                                struct thandle *handle)
4249 {
4250         struct osd_thandle *oh;
4251         int rc;
4252
4253         /* it's possible that object doesn't exist yet */
4254         LASSERT(handle != NULL);
4255
4256         oh = container_of(handle, struct osd_thandle, ot_super);
4257         LASSERT(oh->ot_handle == NULL);
4258
4259         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
4260                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4261
4262         rc = osd_idc_find_and_init(env, osd_dev(dt->do_lu.lo_dev),
4263                                    osd_dt_obj(dt));
4264
4265         return rc;
4266 }
4267
4268 /*
4269  * Concurrency: @dt is write locked.
4270  */
4271 static int osd_ref_add(const struct lu_env *env, struct dt_object *dt,
4272                        struct thandle *th)
4273 {
4274         struct osd_object *obj = osd_dt_obj(dt);
4275         struct inode *inode = obj->oo_inode;
4276         struct osd_thandle *oh;
4277         int rc = 0;
4278
4279         if (!dt_object_exists(dt) || obj->oo_destroyed)
4280                 return -ENOENT;
4281
4282         LINVRNT(osd_invariant(obj));
4283         LASSERT(!dt_object_remote(dt));
4284         LASSERT(osd_is_write_locked(env, obj));
4285         LASSERT(th != NULL);
4286
4287         oh = container_of(th, struct osd_thandle, ot_super);
4288         LASSERT(oh->ot_handle != NULL);
4289
4290         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
4291
4292         CDEBUG(D_INODE, DFID" increase nlink %d\n",
4293                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4294         /*
4295          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
4296          * (65000) subdirectories by storing "1" in i_nlink if the link count
4297          * would otherwise overflow. Directory tranversal tools understand
4298          * that (st_nlink == 1) indicates that the filesystem dose not track
4299          * hard links count on the directory, and will not abort subdirectory
4300          * scanning early once (st_nlink - 2) subdirs have been found.
4301          *
4302          * This also has to properly handle the case of inodes with nlink == 0
4303          * in case they are being linked into the PENDING directory
4304          */
4305         spin_lock(&obj->oo_guard);
4306         if (unlikely(inode->i_nlink == 0))
4307                 /* inc_nlink from 0 may cause WARN_ON */
4308                 set_nlink(inode, 1);
4309         else {
4310                 ldiskfs_inc_count(oh->ot_handle, inode);
4311                 if (!S_ISDIR(inode->i_mode))
4312                         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
4313         }
4314         spin_unlock(&obj->oo_guard);
4315
4316         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4317         LINVRNT(osd_invariant(obj));
4318
4319         osd_trans_exec_check(env, th, OSD_OT_REF_ADD);
4320
4321         return rc;
4322 }
4323
4324 static int osd_declare_ref_del(const struct lu_env *env, struct dt_object *dt,
4325                                struct thandle *handle)
4326 {
4327         struct osd_thandle *oh;
4328
4329         if (!dt_object_exists(dt))
4330                 return -ENOENT;
4331
4332         LASSERT(!dt_object_remote(dt));
4333         LASSERT(handle != NULL);
4334
4335         oh = container_of(handle, struct osd_thandle, ot_super);
4336         LASSERT(oh->ot_handle == NULL);
4337
4338         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
4339                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4340
4341         return 0;
4342 }
4343
4344 /*
4345  * Concurrency: @dt is write locked.
4346  */
4347 static int osd_ref_del(const struct lu_env *env, struct dt_object *dt,
4348                        struct thandle *th)
4349 {
4350         struct osd_object *obj = osd_dt_obj(dt);
4351         struct inode *inode = obj->oo_inode;
4352         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4353         struct osd_thandle *oh;
4354
4355         if (!dt_object_exists(dt))
4356                 return -ENOENT;
4357
4358         LINVRNT(osd_invariant(obj));
4359         LASSERT(!dt_object_remote(dt));
4360         LASSERT(osd_is_write_locked(env, obj));
4361         LASSERT(th != NULL);
4362
4363         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_REF_DEL))
4364                 return -EIO;
4365
4366         oh = container_of(th, struct osd_thandle, ot_super);
4367         LASSERT(oh->ot_handle != NULL);
4368
4369         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
4370
4371         spin_lock(&obj->oo_guard);
4372         /*
4373          * That can be result of upgrade from old Lustre version and
4374          * applied only to local files.  Just skip this ref_del call.
4375          * ext4_unlink() only treats this as a warning, don't LASSERT here.
4376          */
4377         if (inode->i_nlink == 0) {
4378                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
4379                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
4380                              ", maybe an upgraded file? (LU-3915)\n",
4381                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
4382                 spin_unlock(&obj->oo_guard);
4383                 return 0;
4384         }
4385
4386         CDEBUG(D_INODE, DFID" decrease nlink %d\n",
4387                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4388
4389         ldiskfs_dec_count(oh->ot_handle, inode);
4390         spin_unlock(&obj->oo_guard);
4391
4392         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4393         LINVRNT(osd_invariant(obj));
4394
4395         osd_trans_exec_check(env, th, OSD_OT_REF_DEL);
4396
4397         return 0;
4398 }
4399
4400 /*
4401  * Concurrency: @dt is read locked.
4402  */
4403 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
4404                          struct lu_buf *buf, const char *name)
4405 {
4406         struct osd_object      *obj    = osd_dt_obj(dt);
4407         struct inode           *inode  = obj->oo_inode;
4408         struct osd_thread_info *info   = osd_oti_get(env);
4409         struct dentry          *dentry = &info->oti_obj_dentry;
4410         bool cache_xattr = false;
4411         int rc;
4412
4413         LASSERT(buf);
4414
4415         /* version get is not real XATTR but uses xattr API */
4416         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4417                 dt_obj_version_t *ver = buf->lb_buf;
4418
4419                 /*
4420                  * for version we are just using xattr API but change inode
4421                  * field instead
4422                  */
4423                 if (buf->lb_len == 0)
4424                         return sizeof(dt_obj_version_t);
4425
4426                 if (buf->lb_len < sizeof(dt_obj_version_t))
4427                         return -ERANGE;
4428
4429                 CDEBUG(D_INODE, "Get version %#llx for inode %lu\n",
4430                        LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4431
4432                 *ver = LDISKFS_I(inode)->i_fs_version;
4433
4434                 return sizeof(dt_obj_version_t);
4435         }
4436
4437         if (!dt_object_exists(dt))
4438                 return -ENOENT;
4439
4440         LASSERT(!dt_object_remote(dt));
4441         LASSERT(inode->i_op != NULL);
4442 #ifdef HAVE_IOP_XATTR
4443         LASSERT(inode->i_op->getxattr != NULL);
4444 #endif
4445
4446         if (strcmp(name, XATTR_NAME_LOV) == 0 ||
4447             strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
4448                 cache_xattr = true;
4449
4450         if (cache_xattr) {
4451                 rc = osd_oxc_get(obj, name, buf);
4452                 if (rc != -ENOENT)
4453                         return rc;
4454         }
4455
4456         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4457                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4458                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4459                 struct filter_fid *ff;
4460                 struct ost_layout *ol;
4461
4462                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4463                 if (rc)
4464                         return rc;
4465
4466                 LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4467
4468                 rc = sizeof(*ff);
4469                 if (buf->lb_len == 0 || !buf->lb_buf)
4470                         return rc;
4471
4472                 if (buf->lb_len < rc)
4473                         return -ERANGE;
4474
4475                 ff = buf->lb_buf;
4476                 ol = &ff->ff_layout;
4477                 ol->ol_stripe_count = cpu_to_le32(loa->loa_parent_fid.f_ver >>
4478                                                   PFID_STRIPE_IDX_BITS);
4479                 ol->ol_stripe_size = cpu_to_le32(loa->loa_stripe_size);
4480                 loa->loa_parent_fid.f_ver &= PFID_STRIPE_COUNT_MASK;
4481                 fid_cpu_to_le(&ff->ff_parent, &loa->loa_parent_fid);
4482                 if (lma->lma_compat & LMAC_COMP_INFO) {
4483                         ol->ol_comp_start = cpu_to_le64(loa->loa_comp_start);
4484                         ol->ol_comp_end = cpu_to_le64(loa->loa_comp_end);
4485                         ol->ol_comp_id = cpu_to_le32(loa->loa_comp_id);
4486                 } else {
4487                         ol->ol_comp_start = 0;
4488                         ol->ol_comp_end = 0;
4489                         ol->ol_comp_id = 0;
4490                 }
4491         } else {
4492                 rc = __osd_xattr_get(inode, dentry, name,
4493                                      buf->lb_buf, buf->lb_len);
4494         }
4495
4496         if (cache_xattr) {
4497                 if (rc == -ENOENT || rc == -ENODATA)
4498                         osd_oxc_add(obj, name, NULL, 0);
4499                 else if (rc > 0 && buf->lb_buf != NULL)
4500                         osd_oxc_add(obj, name, buf->lb_buf, rc);
4501         }
4502
4503         return rc;
4504 }
4505
4506 static int osd_declare_xattr_set(const struct lu_env *env,
4507                                  struct dt_object *dt,
4508                                  const struct lu_buf *buf, const char *name,
4509                                  int fl, struct thandle *handle)
4510 {
4511         struct osd_thandle *oh;
4512         int credits = 0;
4513         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4514
4515         LASSERT(handle != NULL);
4516
4517         oh = container_of(handle, struct osd_thandle, ot_super);
4518         LASSERT(oh->ot_handle == NULL);
4519
4520         if (strcmp(name, XATTR_NAME_LMA) == 0) {
4521                 /*
4522                  * For non-upgrading case, the LMA is set first and
4523                  * usually fit inode. But for upgrade case, the LMA
4524                  * may be in another separated EA block.
4525                  */
4526                 if (dt_object_exists(dt)) {
4527                         if (fl == LU_XATTR_REPLACE)
4528                                 credits = 1;
4529                         else
4530                                 goto upgrade;
4531                 }
4532         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4533                 credits = 1;
4534         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
4535                 /* We may need to delete the old PFID EA. */
4536                 credits = LDISKFS_MAXQUOTAS_DEL_BLOCKS(sb);
4537                 if (fl == LU_XATTR_REPLACE)
4538                         credits += 1;
4539                 else
4540                         goto upgrade;
4541         } else {
4542                 /*
4543                  * If some name entry resides on remote MDT, then will create
4544                  * agent entry under remote parent. On the other hand, if the
4545                  * remote entry will be removed, then related agent entry may
4546                  * need to be removed from the remote parent. So there may be
4547                  * kinds of cases, let's declare enough credits. The credits
4548                  * for create agent entry is enough for remove case.
4549                  */
4550                 if (strcmp(name, XATTR_NAME_LINK) == 0) {
4551                         credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
4552                         if (dt_object_exists(dt))
4553                                 credits += 1; /* For updating LMA */
4554                 }
4555
4556 upgrade:
4557                 credits += osd_dto_credits_noquota[DTO_XATTR_SET];
4558
4559                 if (buf != NULL) {
4560                         ssize_t buflen;
4561
4562                         if (buf->lb_buf == NULL && dt_object_exists(dt)) {
4563                                 /*
4564                                  * learn xattr size from osd_xattr_get if
4565                                  * attribute has not been read yet
4566                                  */
4567                                 buflen = __osd_xattr_get(
4568                                     osd_dt_obj(dt)->oo_inode,
4569                                     &osd_oti_get(env)->oti_obj_dentry,
4570                                     name, NULL, 0);
4571                                 if (buflen < 0)
4572                                         buflen = 0;
4573                         } else {
4574                                 buflen = buf->lb_len;
4575                         }
4576
4577                         if (buflen > sb->s_blocksize) {
4578                                 credits += osd_calc_bkmap_credits(
4579                                     sb, NULL, 0, -1,
4580                                     (buflen + sb->s_blocksize - 1) >>
4581                                     sb->s_blocksize_bits);
4582                         }
4583                 }
4584                 /*
4585                  * xattr set may involve inode quota change, reserve credits for
4586                  * dquot_initialize()
4587                  */
4588                 credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4589         }
4590
4591         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
4592
4593         return 0;
4594 }
4595
4596 static int osd_xattr_set_pfid(const struct lu_env *env, struct osd_object *obj,
4597                               const struct lu_buf *buf, int fl,
4598                               struct thandle *handle)
4599 {
4600         struct osd_thread_info *info = osd_oti_get(env);
4601         struct dentry *dentry = &info->oti_obj_dentry;
4602         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4603         struct lustre_mdt_attrs *lma = &loa->loa_lma;
4604         struct inode *inode = obj->oo_inode;
4605         struct filter_fid *ff = buf->lb_buf;
4606         struct ost_layout *ol = &ff->ff_layout;
4607         int flags = XATTR_REPLACE;
4608         int rc;
4609
4610         ENTRY;
4611
4612         if (buf->lb_len != sizeof(*ff) && buf->lb_len != sizeof(struct lu_fid))
4613                 RETURN(-EINVAL);
4614
4615         rc = osd_get_lma(info, inode, dentry, loa);
4616         if (rc == -ENODATA) {
4617                 /* Usually for upgarding from old device */
4618                 lustre_loa_init(loa, lu_object_fid(&obj->oo_dt.do_lu),
4619                                 LMAC_FID_ON_OST, 0);
4620                 flags = XATTR_CREATE;
4621         } else if (rc) {
4622                 RETURN(rc);
4623         }
4624
4625         if (!rc && lma->lma_compat & LMAC_STRIPE_INFO) {
4626                 if ((fl & LU_XATTR_CREATE) && !(fl & LU_XATTR_REPLACE))
4627                         RETURN(-EEXIST);
4628
4629                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256) {
4630                         /* Separate PFID EA from LMA */
4631                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4632                         lustre_lma_swab(lma);
4633                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4634                                              sizeof(*lma), XATTR_REPLACE);
4635                         if (!rc) {
4636                                 obj->oo_pfid_in_lma = 0;
4637                                 rc = LU_XATTR_CREATE;
4638                         }
4639
4640                         RETURN(rc);
4641                 }
4642         } else {
4643                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256)
4644                         RETURN(fl);
4645
4646                 /*
4647                  * Old client does not send stripe information,
4648                  * then store the PFID EA on disk separatedly.
4649                  */
4650                 if (unlikely(buf->lb_len == sizeof(struct lu_fid) ||
4651                              ol->ol_stripe_size == 0))
4652                         RETURN(fl);
4653
4654                 /* Remove old PFID EA entry firstly. */
4655                 dquot_initialize(inode);
4656                 rc = ll_vfs_removexattr(dentry, inode, XATTR_NAME_FID);
4657                 if (rc == -ENODATA) {
4658                         /* XATTR_NAME_FID is already absent */
4659                         rc = 0;
4660                 } else if (rc) {
4661                         RETURN(rc);
4662                 }
4663         }
4664
4665         fid_le_to_cpu(&loa->loa_parent_fid, &ff->ff_parent);
4666         if (likely(ol->ol_stripe_size != 0)) {
4667                 loa->loa_parent_fid.f_ver |= le32_to_cpu(ol->ol_stripe_count) <<
4668                                              PFID_STRIPE_IDX_BITS;
4669                 loa->loa_stripe_size = le32_to_cpu(ol->ol_stripe_size);
4670                 lma->lma_compat |= LMAC_STRIPE_INFO;
4671                 if (ol->ol_comp_id != 0) {
4672                         loa->loa_comp_id = le32_to_cpu(ol->ol_comp_id);
4673                         loa->loa_comp_start = le64_to_cpu(ol->ol_comp_start);
4674                         loa->loa_comp_end = le64_to_cpu(ol->ol_comp_end);
4675                         lma->lma_compat |= LMAC_COMP_INFO;
4676                 }
4677         }
4678
4679         lustre_loa_swab(loa, false);
4680
4681         /* Store the PFID EA inside LMA. */
4682         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa, sizeof(*loa),
4683                              flags);
4684         if (!rc)
4685                 obj->oo_pfid_in_lma = 1;
4686
4687         RETURN(rc);
4688 }
4689
4690 /*
4691  * In DNE environment, the object (in spite of regular file or directory)
4692  * and its name entry may reside on different MDTs. Under such case, we will
4693  * create an agent entry on the MDT where the object resides. The agent entry
4694  * references the object locally, that makes the object to be visible to the
4695  * userspace when mounted as 'ldiskfs' directly. Then the userspace tools,
4696  * such as 'tar' can handle the object properly.
4697  *
4698  * We handle the agent entry during set linkEA that is the common interface
4699  * for both regular file and directroy, can handle kinds of cases, such as
4700  * create/link/unlink/rename, and so on.
4701  *
4702  * NOTE: we can NOT do that when ea_{insert,delete} that is only for directory.
4703  *
4704  * XXX: There are two known issues:
4705  * 1. For one object, we will create at most one agent entry even if there
4706  *    may be more than one cross-MDTs hard links on the object. So the local
4707  *    e2fsck may claim that the object's nlink is larger than the name entries
4708  *    that reference such inode. And in further, the e2fsck will fix the nlink
4709  *    attribute to match the local references. Then it will cause the object's
4710  *    nlink attribute to be inconsistent with the global references. it is bad
4711  *    but not fatal. The ref_del() can handle the zero-referenced case. On the
4712  *    other hand, the global namespace LFSCK can repair the object's attribute
4713  *    according to the linkEA.
4714  * 2. There may be too many hard links on the object as to its linkEA overflow,
4715  *    then the linkEA entry for cross-MDTs reference may be discarded. If such
4716  *    case happened, then at this point, we do not know whether there are some
4717  *    cross-MDTs reference. But there are local references, it guarantees that
4718  *    object is visible to userspace when mounted as 'ldiskfs'. That is enough.
4719  */
4720 static int osd_xattr_handle_linkea(const struct lu_env *env,
4721                                    struct osd_device *osd,
4722                                    struct osd_object *obj,
4723                                    const struct lu_buf *buf,
4724                                    struct thandle *handle)
4725 {
4726         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
4727         struct lu_fid *tfid = &osd_oti_get(env)->oti_fid3;
4728         struct linkea_data ldata = { .ld_buf = (struct lu_buf *)buf };
4729         struct lu_name tmpname;
4730         struct osd_thandle *oh;
4731         int rc;
4732         bool remote = false;
4733
4734         ENTRY;
4735
4736         oh = container_of(handle, struct osd_thandle, ot_super);
4737         LASSERT(oh->ot_handle != NULL);
4738
4739         rc = linkea_init_with_rec(&ldata);
4740         if (!rc) {
4741                 linkea_first_entry(&ldata);
4742                 while (ldata.ld_lee != NULL && !remote) {
4743                         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen,
4744                                             &tmpname, tfid);
4745                         if (osd_remote_fid(env, osd, tfid) > 0)
4746                                 remote = true;
4747                         else
4748                                 linkea_next_entry(&ldata);
4749                 }
4750         } else if (rc == -ENODATA) {
4751                 rc = 0;
4752         } else {
4753                 RETURN(rc);
4754         }
4755
4756         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu) && !remote) {
4757                 rc = osd_delete_from_remote_parent(env, osd, obj, oh, false);
4758                 if (rc)
4759                         CERROR("%s: failed to remove agent entry for "DFID
4760                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4761         } else if (!lu_object_has_agent_entry(&obj->oo_dt.do_lu) && remote) {
4762                 rc = osd_add_to_remote_parent(env, osd, obj, oh);
4763                 if (rc)
4764                         CERROR("%s: failed to create agent entry for "DFID
4765                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4766         }
4767
4768         RETURN(rc);
4769 }
4770
4771 /*
4772  * Concurrency: @dt is write locked.
4773  */
4774 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
4775                          const struct lu_buf *buf, const char *name, int fl,
4776                          struct thandle *handle)
4777 {
4778         struct osd_object *obj = osd_dt_obj(dt);
4779         struct osd_device *osd = osd_obj2dev(obj);
4780         struct inode *inode = obj->oo_inode;
4781         struct osd_thread_info *info = osd_oti_get(env);
4782         int fs_flags = 0;
4783         int len;
4784         int rc;
4785
4786         ENTRY;
4787
4788         LASSERT(handle);
4789         LASSERT(buf);
4790
4791         /* version set is not real XATTR */
4792         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4793                 dt_obj_version_t *version = buf->lb_buf;
4794
4795                 /*
4796                  * for version we are just using xattr API but change inode
4797                  * field instead
4798                  */
4799                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
4800
4801                 CDEBUG(D_INODE, "Set version %#llx (old %#llx) for inode %lu\n",
4802                        *version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4803
4804                 LDISKFS_I(inode)->i_fs_version = *version;
4805                 /*
4806                  * Version is set after all inode operations are finished,
4807                  * so we should mark it dirty here
4808                  */
4809                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4810
4811                 RETURN(0);
4812         }
4813
4814         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zu\n",
4815                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
4816
4817         len = buf->lb_len;
4818         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4819
4820         /*
4821          * For the OST device with 256 bytes inode size by default,
4822          * the PFID EA will be stored together with LMA EA to avoid
4823          * performance trouble. Otherwise the PFID EA can be stored
4824          * independently. LU-8998
4825          */
4826         if (strcmp(name, XATTR_NAME_FID) == 0 && osd->od_is_ost &&
4827             (LDISKFS_INODE_SIZE(inode->i_sb) <= 256 || obj->oo_pfid_in_lma)) {
4828                 LASSERT(buf->lb_buf);
4829
4830                 fl = osd_xattr_set_pfid(env, obj, buf, fl, handle);
4831                 if (fl <= 0)
4832                         RETURN(fl);
4833         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
4834                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4835                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4836
4837                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4838                 if (rc)
4839                         RETURN(rc);
4840
4841                 lma->lma_incompat |= LMAI_STRIPED;
4842                 lustre_lma_swab(lma);
4843                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4844                                      sizeof(*lma), XATTR_REPLACE);
4845                 if (rc != 0)
4846                         RETURN(rc);
4847         } else if (strcmp(name, XATTR_NAME_LINK) == 0) {
4848                 LASSERT(!osd->od_is_ost);
4849
4850                 rc = osd_xattr_handle_linkea(env, osd, obj, buf, handle);
4851                 if (rc)
4852                         RETURN(rc);
4853         }
4854
4855         if (fl & LU_XATTR_REPLACE)
4856                 fs_flags |= XATTR_REPLACE;
4857
4858         if (fl & LU_XATTR_CREATE)
4859                 fs_flags |= XATTR_CREATE;
4860
4861         rc = __osd_xattr_set(info, inode, name, buf->lb_buf, len, fs_flags);
4862         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4863
4864         if (rc == 0 &&
4865             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4866              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4867                 osd_oxc_add(obj, name, buf->lb_buf, buf->lb_len);
4868
4869         return rc;
4870 }
4871
4872 /*
4873  * Concurrency: @dt is read locked.
4874  */
4875 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
4876                           const struct lu_buf *buf)
4877 {
4878         struct osd_object *obj = osd_dt_obj(dt);
4879         struct inode *inode = obj->oo_inode;
4880         struct osd_thread_info *info = osd_oti_get(env);
4881         struct dentry *dentry = &info->oti_obj_dentry;
4882
4883         if (!dt_object_exists(dt))
4884                 return -ENOENT;
4885
4886         LASSERT(!dt_object_remote(dt));
4887         LASSERT(inode->i_op != NULL);
4888         LASSERT(inode->i_op->listxattr != NULL);
4889
4890         dentry->d_inode = inode;
4891         dentry->d_sb = inode->i_sb;
4892         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
4893 }
4894
4895 static int osd_declare_xattr_del(const struct lu_env *env,
4896                                  struct dt_object *dt, const char *name,
4897                                  struct thandle *handle)
4898 {
4899         struct osd_thandle *oh;
4900         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4901
4902         LASSERT(!dt_object_remote(dt));
4903         LASSERT(handle != NULL);
4904
4905         oh = container_of(handle, struct osd_thandle, ot_super);
4906         LASSERT(oh->ot_handle == NULL);
4907
4908         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
4909                              osd_dto_credits_noquota[DTO_XATTR_SET]);
4910         /*
4911          * xattr del may involve inode quota change, reserve credits for
4912          * dquot_initialize()
4913          */
4914         oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4915
4916         return 0;
4917 }
4918
4919 /*
4920  * Concurrency: @dt is write locked.
4921  */
4922 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
4923                          const char *name, struct thandle *handle)
4924 {
4925         struct osd_object *obj = osd_dt_obj(dt);
4926         struct inode *inode = obj->oo_inode;
4927         struct osd_thread_info *info = osd_oti_get(env);
4928         struct dentry *dentry = &info->oti_obj_dentry;
4929         int rc;
4930
4931         if (!dt_object_exists(dt))
4932                 return -ENOENT;
4933
4934         LASSERT(!dt_object_remote(dt));
4935         LASSERT(inode->i_op != NULL);
4936         LASSERT(handle != NULL);
4937 #ifdef HAVE_IOP_XATTR
4938         LASSERT(inode->i_op->removexattr != NULL);
4939 #endif
4940
4941         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4942
4943         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4944                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
4945
4946                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
4947                                  &info->oti_ost_attrs);
4948                 if (!rc) {
4949                         LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4950
4951                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4952                         lustre_lma_swab(lma);
4953                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4954                                              sizeof(*lma), XATTR_REPLACE);
4955                         if (!rc)
4956                                 obj->oo_pfid_in_lma = 0;
4957                 }
4958         } else {
4959                 dquot_initialize(inode);
4960                 dentry->d_inode = inode;
4961                 dentry->d_sb = inode->i_sb;
4962                 rc = ll_vfs_removexattr(dentry, inode, name);
4963         }
4964
4965         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4966
4967         if (rc == 0 &&
4968             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4969              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4970                 osd_oxc_del(obj, name);
4971
4972         return rc;
4973 }
4974
4975 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt,
4976                            __u64 start, __u64 end)
4977 {
4978         struct osd_object *obj = osd_dt_obj(dt);
4979         struct inode *inode = obj->oo_inode;
4980         struct file *file = osd_quasi_file(env, inode);
4981         int rc;
4982
4983         ENTRY;
4984
4985         rc = vfs_fsync_range(file, start, end, 0);
4986
4987         RETURN(rc);
4988 }
4989
4990 static int osd_invalidate(const struct lu_env *env, struct dt_object *dt)
4991 {
4992         return 0;
4993 }
4994
4995 static bool osd_check_stale(struct dt_object *dt)
4996 {
4997         return false;
4998 }
4999 /*
5000  * Index operations.
5001  */
5002
5003 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
5004                                const struct dt_index_features *feat)
5005 {
5006         struct iam_descr *descr;
5007
5008         if (osd_object_is_root(o))
5009                 return feat == &dt_directory_features;
5010
5011         LASSERT(o->oo_dir != NULL);
5012
5013         descr = o->oo_dir->od_container.ic_descr;
5014         if (feat == &dt_directory_features) {
5015                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
5016                         return 1;
5017                 else
5018                         return 0;
5019         } else {
5020                 return feat->dif_keysize_min <= descr->id_key_size &&
5021                        descr->id_key_size <= feat->dif_keysize_max &&
5022                        feat->dif_recsize_min <= descr->id_rec_size &&
5023                        descr->id_rec_size <= feat->dif_recsize_max &&
5024                        !(feat->dif_flags & (DT_IND_VARKEY |
5025                                             DT_IND_VARREC | DT_IND_NONUNQ)) &&
5026                        ergo(feat->dif_flags & DT_IND_UPDATE,
5027                             1 /* XXX check that object (and fs) is writable */);
5028         }
5029 }
5030
5031 static int osd_iam_container_init(const struct lu_env *env,
5032                                   struct osd_object *obj,
5033                                   struct osd_directory *dir)
5034 {
5035         struct iam_container *bag = &dir->od_container;
5036         int result;
5037
5038         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
5039         if (result != 0)
5040                 return result;
5041
5042         result = iam_container_setup(bag);
5043         if (result == 0)
5044                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
5045         else
5046                 iam_container_fini(bag);
5047
5048         return result;
5049 }
5050
5051
5052 /*
5053  * Concurrency: no external locking is necessary.
5054  */
5055 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
5056                          const struct dt_index_features *feat)
5057 {
5058         int result;
5059         int skip_iam = 0;
5060         struct osd_object *obj = osd_dt_obj(dt);
5061
5062         LINVRNT(osd_invariant(obj));
5063
5064         if (osd_object_is_root(obj)) {
5065                 dt->do_index_ops = &osd_index_ea_ops;
5066                 result = 0;
5067         } else if (feat == &dt_directory_features) {
5068                 dt->do_index_ops = &osd_index_ea_ops;
5069                 if (obj->oo_inode == NULL || S_ISDIR(obj->oo_inode->i_mode))
5070                         result = 0;
5071                 else
5072                         result = -ENOTDIR;
5073                 skip_iam = 1;
5074         } else if (unlikely(feat == &dt_otable_features)) {
5075                 dt->do_index_ops = &osd_otable_ops;
5076                 return 0;
5077         } else if (unlikely(feat == &dt_acct_features)) {
5078                 dt->do_index_ops = &osd_acct_index_ops;
5079                 result = 0;
5080                 skip_iam = 1;
5081         } else if (!osd_has_index(obj)) {
5082                 struct osd_directory *dir;
5083                 struct osd_device *osd = osd_obj2dev(obj);
5084                 const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
5085
5086                 OBD_ALLOC_PTR(dir);
5087                 if (dir) {
5088
5089                         spin_lock(&obj->oo_guard);
5090                         if (obj->oo_dir == NULL)
5091                                 obj->oo_dir = dir;
5092                         else
5093                                 /*
5094                                  * Concurrent thread allocated container data.
5095                                  */
5096                                 OBD_FREE_PTR(dir);
5097                         spin_unlock(&obj->oo_guard);
5098                         /*
5099                          * Now, that we have container data, serialize its
5100                          * initialization.
5101                          */
5102                         down_write(&obj->oo_ext_idx_sem);
5103                         /*
5104                          * recheck under lock.
5105                          */
5106
5107                         if (osd_has_index(obj)) {
5108                                 result = 0;
5109                                 goto unlock;
5110                         }
5111
5112                         result = osd_iam_container_init(env, obj, obj->oo_dir);
5113                         if (result || feat == &dt_lfsck_namespace_features ||
5114                             feat == &dt_lfsck_layout_orphan_features ||
5115                             feat == &dt_lfsck_layout_dangling_features)
5116                                 goto unlock;
5117
5118                         result = osd_index_register(osd, fid,
5119                                                     feat->dif_keysize_max,
5120                                                     feat->dif_recsize_max);
5121                         if (result < 0)
5122                                 CWARN("%s: failed to register index "
5123                                       DFID": rc = %d\n",
5124                                       osd_name(osd), PFID(fid), result);
5125                         else if (result > 0)
5126                                 result = 0;
5127                         else
5128                                 CDEBUG(D_LFSCK, "%s: index object "DFID
5129                                        " (%d/%d) registered\n",
5130                                        osd_name(osd), PFID(fid),
5131                                        (int)feat->dif_keysize_max,
5132                                        (int)feat->dif_recsize_max);
5133
5134 unlock:
5135                         up_write(&obj->oo_ext_idx_sem);
5136                 } else {
5137                         result = -ENOMEM;
5138                 }
5139         } else {
5140                 result = 0;
5141         }
5142
5143         if (result == 0 && skip_iam == 0) {
5144                 if (!osd_iam_index_probe(env, obj, feat))
5145                         result = -ENOTDIR;
5146         }
5147         LINVRNT(osd_invariant(obj));
5148
5149         return result;
5150 }
5151
5152 static int osd_otable_it_attr_get(const struct lu_env *env,
5153                                  struct dt_object *dt,
5154                                  struct lu_attr *attr)
5155 {
5156         attr->la_valid = 0;
5157         return 0;
5158 }
5159
5160 static const struct dt_object_operations osd_obj_ops = {
5161         .do_read_lock           = osd_read_lock,
5162         .do_write_lock          = osd_write_lock,
5163         .do_read_unlock         = osd_read_unlock,
5164         .do_write_unlock        = osd_write_unlock,
5165         .do_write_locked        = osd_write_locked,
5166         .do_attr_get            = osd_attr_get,
5167         .do_declare_attr_set    = osd_declare_attr_set,
5168         .do_attr_set            = osd_attr_set,
5169         .do_ah_init             = osd_ah_init,
5170         .do_declare_create      = osd_declare_create,
5171         .do_create              = osd_create,
5172         .do_declare_destroy     = osd_declare_destroy,
5173         .do_destroy             = osd_destroy,
5174         .do_index_try           = osd_index_try,
5175         .do_declare_ref_add     = osd_declare_ref_add,
5176         .do_ref_add             = osd_ref_add,
5177         .do_declare_ref_del     = osd_declare_ref_del,
5178         .do_ref_del             = osd_ref_del,
5179         .do_xattr_get           = osd_xattr_get,
5180         .do_declare_xattr_set   = osd_declare_xattr_set,
5181         .do_xattr_set           = osd_xattr_set,
5182         .do_declare_xattr_del   = osd_declare_xattr_del,
5183         .do_xattr_del           = osd_xattr_del,
5184         .do_xattr_list          = osd_xattr_list,
5185         .do_object_sync         = osd_object_sync,
5186         .do_invalidate          = osd_invalidate,
5187         .do_check_stale         = osd_check_stale,
5188 };
5189
5190 static const struct dt_object_operations osd_obj_otable_it_ops = {
5191         .do_attr_get    = osd_otable_it_attr_get,
5192         .do_index_try   = osd_index_try,
5193 };
5194
5195 static int osd_index_declare_iam_delete(const struct lu_env *env,
5196                                         struct dt_object *dt,
5197                                         const struct dt_key *key,
5198                                         struct thandle *handle)
5199 {
5200         struct osd_thandle *oh;
5201
5202         oh = container_of(handle, struct osd_thandle, ot_super);
5203         LASSERT(oh->ot_handle == NULL);
5204
5205         /* Recycle  may cause additional three blocks to be changed. */
5206         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
5207                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
5208
5209         return 0;
5210 }
5211
5212 /**
5213  *      delete a (key, value) pair from index \a dt specified by \a key
5214  *
5215  *      \param  dt      osd index object
5216  *      \param  key     key for index
5217  *      \param  rec     record reference
5218  *      \param  handle  transaction handler
5219  *
5220  *      \retval  0  success
5221  *      \retval -ve   failure
5222  */
5223 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
5224                                 const struct dt_key *key,
5225                                 struct thandle *handle)
5226 {
5227         struct osd_thread_info *oti = osd_oti_get(env);
5228         struct osd_object *obj = osd_dt_obj(dt);
5229         struct osd_thandle *oh;
5230         struct iam_path_descr *ipd;
5231         struct iam_container *bag = &obj->oo_dir->od_container;
5232         int rc;
5233
5234         ENTRY;
5235
5236         if (!dt_object_exists(dt))
5237                 RETURN(-ENOENT);
5238
5239         LINVRNT(osd_invariant(obj));
5240         LASSERT(!dt_object_remote(dt));
5241         LASSERT(bag->ic_object == obj->oo_inode);
5242         LASSERT(handle != NULL);
5243
5244         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5245
5246         ipd = osd_idx_ipd_get(env, bag);
5247         if (unlikely(ipd == NULL))
5248                 RETURN(-ENOMEM);
5249
5250         oh = container_of(handle, struct osd_thandle, ot_super);
5251         LASSERT(oh->ot_handle != NULL);
5252         LASSERT(oh->ot_handle->h_transaction != NULL);
5253
5254         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5255                 /* swab quota uid/gid provided by caller */
5256                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5257                 key = (const struct dt_key *)&oti->oti_quota_id;
5258         }
5259
5260         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
5261         osd_ipd_put(env, bag, ipd);
5262         LINVRNT(osd_invariant(obj));
5263         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5264         RETURN(rc);
5265 }
5266
5267 static int osd_index_declare_ea_delete(const struct lu_env *env,
5268                                        struct dt_object *dt,
5269                                        const struct dt_key *key,
5270                                        struct thandle *handle)
5271 {
5272         struct osd_thandle *oh;
5273         struct inode *inode;
5274         int rc, credits;
5275
5276         ENTRY;
5277
5278         LASSERT(!dt_object_remote(dt));
5279         LASSERT(handle != NULL);
5280
5281         oh = container_of(handle, struct osd_thandle, ot_super);
5282         LASSERT(oh->ot_handle == NULL);
5283
5284         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE];
5285         osd_trans_declare_op(env, oh, OSD_OT_DELETE, credits);
5286
5287         inode = osd_dt_obj(dt)->oo_inode;
5288         if (inode == NULL)
5289                 RETURN(-ENOENT);
5290
5291         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
5292                                    i_projid_read(inode), 0, oh, osd_dt_obj(dt),
5293                                    NULL, OSD_QID_BLK);
5294         RETURN(rc);
5295 }
5296
5297 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
5298                                           struct dt_rec *fid)
5299 {
5300         struct osd_fid_pack *rec;
5301         int rc = -ENODATA;
5302
5303         if (de->file_type & LDISKFS_DIRENT_LUFID) {
5304                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
5305                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
5306                 if (rc == 0 && unlikely(!fid_is_sane((struct lu_fid *)fid)))
5307                         rc = -EINVAL;
5308         }
5309         return rc;
5310 }
5311
5312 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
5313                           const struct lu_fid *fid)
5314 {
5315         struct seq_server_site *ss = osd_seq_site(osd);
5316
5317         ENTRY;
5318
5319         /* FID seqs not in FLDB, must be local seq */
5320         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
5321                 RETURN(0);
5322
5323         /*
5324          * If FLD is not being initialized yet, it only happens during the
5325          * initialization, likely during mgs initialization, and we assume
5326          * this is local FID.
5327          */
5328         if (ss == NULL || ss->ss_server_fld == NULL)
5329                 RETURN(0);
5330
5331         /* Only check the local FLDB here */
5332         if (osd_seq_exists(env, osd, fid_seq(fid)))
5333                 RETURN(0);
5334
5335         RETURN(1);
5336 }
5337
5338 static void osd_take_care_of_agent(const struct lu_env *env,
5339                                    struct osd_device *osd,
5340                                    struct osd_thandle *oh,
5341                                    struct ldiskfs_dir_entry_2 *de)
5342 {
5343         struct lu_fid *fid = &osd_oti_get(env)->oti_fid;
5344         struct osd_idmap_cache *idc;
5345         int rc, schedule = 0;
5346
5347         LASSERT(de != NULL);
5348
5349         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
5350         if (likely(rc == 0)) {
5351                 idc = osd_idc_find_or_init(env, osd, fid);
5352                 if (IS_ERR(idc) || idc->oic_remote)
5353                         schedule = 1;
5354         } else if (rc == -ENODATA) {
5355                 /*
5356                  * can't get FID, postpone to the end of the
5357                  * transaction when iget() is safe
5358                  */
5359                 schedule = 1;
5360         } else {
5361                 CERROR("%s: can't get FID: rc = %d\n", osd_name(osd), rc);
5362         }
5363         if (schedule)
5364                 osd_schedule_agent_inode_removal(env, oh,
5365                                                  le32_to_cpu(de->inode));
5366 }
5367
5368 /**
5369  * Utility function to get real name from object name
5370  *
5371  * \param[in] obj      pointer to the object to be handled
5372  * \param[in] name     object name
5373  * \param[in] len      object name len
5374  * \param[out]ln       pointer to the struct lu_name to hold the real name
5375  *
5376  * If file is not encrypted, real name is just the object name.
5377  * If file is encrypted, object name needs to be decoded. In
5378  * this case a new buffer is allocated, and ln->ln_name needs to be freed by
5379  * the caller.
5380  *
5381  * \retval   0, on success
5382  * \retval -ve, on error
5383  */
5384 static int obj_name2lu_name(struct osd_object *obj, const char *name,
5385                             int len, struct lu_name *ln)
5386 {
5387         struct lu_fid namefid;
5388
5389         fid_zero(&namefid);
5390
5391         if (name[0] == '[')
5392                 sscanf(name + 1, SFID, RFID(&namefid));
5393
5394         if (fid_is_sane(&namefid) || name_is_dot_or_dotdot(name, len) ||
5395             !(obj->oo_lma_flags & LUSTRE_ENCRYPT_FL)) {
5396                 ln->ln_name = name;
5397                 ln->ln_namelen = len;
5398         } else {
5399                 char *buf = kmalloc(len, GFP_NOFS);
5400
5401                 if (!buf)
5402                         return -ENOMEM;
5403
5404                 len = critical_decode(name, len, buf);
5405                 ln->ln_name = buf;
5406                 ln->ln_namelen = len;
5407         }
5408
5409         return 0;
5410 }
5411
5412 /**
5413  * Index delete function for interoperability mode (b11826).
5414  * It will remove the directory entry added by osd_index_ea_insert().
5415  * This entry is needed to maintain name->fid mapping.
5416  *
5417  * \param key,  key i.e. file entry to be deleted
5418  *
5419  * \retval   0, on success
5420  * \retval -ve, on error
5421  */
5422 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
5423                                const struct dt_key *key, struct thandle *handle)
5424 {
5425         struct osd_object *obj = osd_dt_obj(dt);
5426         struct inode *dir = obj->oo_inode;
5427         struct dentry *dentry;
5428         struct osd_thandle *oh;
5429         struct ldiskfs_dir_entry_2 *de = NULL;
5430         struct buffer_head *bh;
5431         struct htree_lock *hlock = NULL;
5432         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
5433         struct lu_name ln;
5434         int rc;
5435
5436         ENTRY;
5437
5438         if (!dt_object_exists(dt))
5439                 RETURN(-ENOENT);
5440
5441         LINVRNT(osd_invariant(obj));
5442         LASSERT(!dt_object_remote(dt));
5443         LASSERT(handle != NULL);
5444
5445         rc = obj_name2lu_name(obj, (char *)key, strlen((char *)key), &ln);
5446         if (rc)
5447                 RETURN(rc);
5448
5449         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5450
5451         oh = container_of(handle, struct osd_thandle, ot_super);
5452         LASSERT(oh->ot_handle != NULL);
5453         LASSERT(oh->ot_handle->h_transaction != NULL);
5454
5455         dquot_initialize(dir);
5456         dentry = osd_child_dentry_get(env, obj, ln.ln_name, ln.ln_namelen);
5457
5458         if (obj->oo_hl_head != NULL) {
5459                 hlock = osd_oti_get(env)->oti_hlock;
5460                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5461                                    dir, LDISKFS_HLOCK_DEL);
5462         } else {
5463                 down_write(&obj->oo_ext_idx_sem);
5464         }
5465
5466         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5467         if (!IS_ERR(bh)) {
5468                 /*
5469                  * If this is not the ".." entry, it might be a remote DNE
5470                  * entry and  we need to check if the FID is for a remote
5471                  * MDT.  If the FID is  not in the directory entry (e.g.
5472                  * upgraded 1.8 filesystem without dirdata enabled) then
5473                  * we need to get the FID from the LMA. For a remote directory
5474                  * there HAS to be an LMA, it cannot be an IGIF inode in this
5475                  * case.
5476                  *
5477                  * Delete the entry before the agent inode in order to
5478                  * simplify error handling.  At worst an error after deleting
5479                  * the entry first might leak the agent inode afterward. The
5480                  * reverse would need filesystem abort in case of error deleting
5481                  * the entry after the agent had been removed, or leave a
5482                  * dangling entry pointing at a random inode.
5483                  */
5484                 if (strcmp((char *)key, dotdot) != 0)
5485                         osd_take_care_of_agent(env, osd, oh, de);
5486                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
5487                 brelse(bh);
5488         } else {
5489                 rc = PTR_ERR(bh);
5490         }
5491
5492         if (!rc && fid_is_namespace_visible(lu_object_fid(&dt->do_lu)) &&
5493             obj->oo_dirent_count != LU_DIRENT_COUNT_UNSET) {
5494                 /* NB, dirent count may not be accurate, because it's counted
5495                  * without lock.
5496                  */
5497                 if (obj->oo_dirent_count)
5498                         obj->oo_dirent_count--;
5499                 else
5500                         obj->oo_dirent_count = LU_DIRENT_COUNT_UNSET;
5501         }
5502         if (hlock != NULL)
5503                 ldiskfs_htree_unlock(hlock);
5504         else
5505                 up_write(&obj->oo_ext_idx_sem);
5506         GOTO(out, rc);
5507 out:
5508         LASSERT(osd_invariant(obj));
5509         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5510         if (ln.ln_name != (char *)key)
5511                 kfree(ln.ln_name);
5512         RETURN(rc);
5513 }
5514
5515 /**
5516  *      Lookup index for \a key and copy record to \a rec.
5517  *
5518  *      \param  dt      osd index object
5519  *      \param  key     key for index
5520  *      \param  rec     record reference
5521  *
5522  *      \retval  +ve  success : exact mach
5523  *      \retval  0    return record with key not greater than \a key
5524  *      \retval -ve   failure
5525  */
5526 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
5527                                 struct dt_rec *rec, const struct dt_key *key)
5528 {
5529         struct osd_object *obj = osd_dt_obj(dt);
5530         struct iam_path_descr *ipd;
5531         struct iam_container *bag = &obj->oo_dir->od_container;
5532         struct osd_thread_info *oti = osd_oti_get(env);
5533         struct iam_iterator *it = &oti->oti_idx_it;
5534         struct iam_rec *iam_rec;
5535         int rc;
5536
5537         ENTRY;
5538
5539         if (!dt_object_exists(dt))
5540                 RETURN(-ENOENT);
5541
5542         LASSERT(osd_invariant(obj));
5543         LASSERT(!dt_object_remote(dt));
5544         LASSERT(bag->ic_object == obj->oo_inode);
5545
5546         ipd = osd_idx_ipd_get(env, bag);
5547         if (IS_ERR(ipd))
5548                 RETURN(-ENOMEM);
5549
5550         /* got ipd now we can start iterator. */
5551         iam_it_init(it, bag, 0, ipd);
5552
5553         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5554                 /* swab quota uid/gid provided by caller */
5555                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5556                 key = (const struct dt_key *)&oti->oti_quota_id;
5557         }
5558
5559         rc = iam_it_get(it, (struct iam_key *)key);
5560         if (rc >= 0) {
5561                 if (S_ISDIR(obj->oo_inode->i_mode))
5562                         iam_rec = (struct iam_rec *)oti->oti_ldp;
5563                 else
5564                         iam_rec = (struct iam_rec *)rec;
5565
5566                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
5567
5568                 if (S_ISDIR(obj->oo_inode->i_mode))
5569                         osd_fid_unpack((struct lu_fid *)rec,
5570                                        (struct osd_fid_pack *)iam_rec);
5571                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
5572                         osd_quota_unpack(obj, rec);
5573         }
5574
5575         iam_it_put(it);
5576         iam_it_fini(it);
5577         osd_ipd_put(env, bag, ipd);
5578
5579         LINVRNT(osd_invariant(obj));
5580
5581         RETURN(rc);
5582 }
5583
5584 static int osd_index_declare_iam_insert(const struct lu_env *env,
5585                                         struct dt_object *dt,
5586                                         const struct dt_rec *rec,
5587                                         const struct dt_key *key,
5588                                         struct thandle *handle)
5589 {
5590         struct osd_thandle *oh;
5591
5592         LASSERT(handle != NULL);
5593
5594         oh = container_of(handle, struct osd_thandle, ot_super);
5595         LASSERT(oh->ot_handle == NULL);
5596
5597         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
5598                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
5599
5600         return 0;
5601 }
5602
5603 /**
5604  *      Inserts (key, value) pair in \a dt index object.
5605  *
5606  *      \param  dt      osd index object
5607  *      \param  key     key for index
5608  *      \param  rec     record reference
5609  *      \param  th      transaction handler
5610  *
5611  *      \retval  0  success
5612  *      \retval -ve failure
5613  */
5614 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
5615                                 const struct dt_rec *rec,
5616                                 const struct dt_key *key, struct thandle *th)
5617 {
5618         struct osd_object *obj = osd_dt_obj(dt);
5619         struct iam_path_descr *ipd;
5620         struct osd_thandle *oh;
5621         struct iam_container *bag;
5622         struct osd_thread_info *oti = osd_oti_get(env);
5623         struct iam_rec *iam_rec;
5624         int rc;
5625
5626         ENTRY;
5627
5628         if (!dt_object_exists(dt))
5629                 RETURN(-ENOENT);
5630
5631         LINVRNT(osd_invariant(obj));
5632         LASSERT(!dt_object_remote(dt));
5633
5634         bag = &obj->oo_dir->od_container;
5635         LASSERT(bag->ic_object == obj->oo_inode);
5636         LASSERT(th != NULL);
5637
5638         osd_trans_exec_op(env, th, OSD_OT_INSERT);
5639
5640         ipd = osd_idx_ipd_get(env, bag);
5641         if (unlikely(ipd == NULL))
5642                 RETURN(-ENOMEM);
5643
5644         oh = container_of(th, struct osd_thandle, ot_super);
5645         LASSERT(oh->ot_handle != NULL);
5646         LASSERT(oh->ot_handle->h_transaction != NULL);
5647         if (S_ISDIR(obj->oo_inode->i_mode)) {
5648                 iam_rec = (struct iam_rec *)oti->oti_ldp;
5649                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec,
5650                              &oti->oti_fid);
5651         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5652                 /* pack quota uid/gid */
5653                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5654                 key = (const struct dt_key *)&oti->oti_quota_id;
5655                 /* pack quota record */
5656                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
5657                 iam_rec = (struct iam_rec *)rec;
5658         } else {
5659                 iam_rec = (struct iam_rec *)rec;
5660         }
5661
5662         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
5663                         iam_rec, ipd);
5664         osd_ipd_put(env, bag, ipd);
5665         LINVRNT(osd_invariant(obj));
5666         osd_trans_exec_check(env, th, OSD_OT_INSERT);
5667         RETURN(rc);
5668 }
5669
5670 /**
5671  * Calls ldiskfs_add_entry() to add directory entry
5672  * into the directory. This is required for
5673  * interoperability mode (b11826)
5674  *
5675  * \retval   0, on success
5676  * \retval -ve, on error
5677  */
5678 static int __osd_ea_add_rec(struct osd_thread_info *info,
5679                             struct osd_object *pobj, struct inode  *cinode,
5680                             const char *name, const struct lu_fid *fid,
5681                             struct htree_lock *hlock, struct thandle *th)
5682 {
5683         struct ldiskfs_dentry_param *ldp;
5684         struct dentry *child;
5685         struct osd_thandle *oth;
5686         struct lu_name ln;
5687         int rc;
5688
5689         oth = container_of(th, struct osd_thandle, ot_super);
5690         LASSERT(oth->ot_handle != NULL);
5691         LASSERT(oth->ot_handle->h_transaction != NULL);
5692         LASSERT(pobj->oo_inode);
5693
5694         rc = obj_name2lu_name(pobj, name, strlen(name), &ln);
5695         if (rc)
5696                 RETURN(rc);
5697
5698         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
5699         if (unlikely(osd_object_is_root(pobj)))
5700                 ldp->edp_magic = 0;
5701         else
5702                 osd_get_ldiskfs_dirent_param(ldp, fid);
5703         child = osd_child_dentry_get(info->oti_env, pobj,
5704                                      ln.ln_name, ln.ln_namelen);
5705         child->d_fsdata = (void *)ldp;
5706         dquot_initialize(pobj->oo_inode);
5707         rc = osd_ldiskfs_add_entry(info, osd_obj2dev(pobj), oth->ot_handle,
5708                                    child, cinode, hlock);
5709         if (rc == 0 && OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_TYPE)) {
5710                 struct ldiskfs_dir_entry_2      *de;
5711                 struct buffer_head              *bh;
5712                 int                              rc1;
5713
5714                 bh = osd_ldiskfs_find_entry(pobj->oo_inode, &child->d_name, &de,
5715                                             NULL, hlock);
5716                 if (!IS_ERR(bh)) {
5717                         rc1 = ldiskfs_journal_get_write_access(oth->ot_handle,
5718                                                                bh);
5719                         if (rc1 == 0) {
5720                                 if (S_ISDIR(cinode->i_mode))
5721                                         de->file_type = LDISKFS_DIRENT_LUFID |
5722                                                         LDISKFS_FT_REG_FILE;
5723                                 else
5724                                         de->file_type = LDISKFS_DIRENT_LUFID |
5725                                                         LDISKFS_FT_DIR;
5726                                 ldiskfs_handle_dirty_metadata(oth->ot_handle,
5727                                                               NULL, bh);
5728                         }
5729                         brelse(bh);
5730                 }
5731         }
5732
5733         if (ln.ln_name != name)
5734                 kfree(ln.ln_name);
5735         RETURN(rc);
5736 }
5737
5738 /**
5739  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
5740  * into the directory.Also sets flags into osd object to
5741  * indicate dot and dotdot are created. This is required for
5742  * interoperability mode (b11826)
5743  *
5744  * \param dir   directory for dot and dotdot fixup.
5745  * \param obj   child object for linking
5746  *
5747  * \retval   0, on success
5748  * \retval -ve, on error
5749  */
5750 static int osd_add_dot_dotdot(struct osd_thread_info *info,
5751                               struct osd_object *dir,
5752                               struct inode *parent_dir, const char *name,
5753                               const struct lu_fid *dot_fid,
5754                               const struct lu_fid *dot_dot_fid,
5755                               struct thandle *th)
5756 {
5757         struct inode *inode = dir->oo_inode;
5758         struct osd_thandle *oth;
5759         int result = 0;
5760
5761         oth = container_of(th, struct osd_thandle, ot_super);
5762         LASSERT(oth->ot_handle->h_transaction != NULL);
5763         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
5764
5765         if (strcmp(name, dot) == 0) {
5766                 if (dir->oo_compat_dot_created) {
5767                         result = -EEXIST;
5768                 } else {
5769                         LASSERT(inode->i_ino == parent_dir->i_ino);
5770                         dir->oo_compat_dot_created = 1;
5771                         result = 0;
5772                 }
5773         } else if (strcmp(name, dotdot) == 0) {
5774                 if (!dir->oo_compat_dot_created)
5775                         return -EINVAL;
5776                 /* in case of rename, dotdot is already created */
5777                 if (dir->oo_compat_dotdot_created) {
5778                         return __osd_ea_add_rec(info, dir, parent_dir, name,
5779                                                 dot_dot_fid, NULL, th);
5780                 }
5781
5782                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
5783                         struct lu_fid tfid = *dot_dot_fid;
5784
5785                         tfid.f_oid--;
5786                         result = osd_add_dot_dotdot_internal(info,
5787                                         dir->oo_inode, parent_dir, dot_fid,
5788                                         &tfid, oth);
5789                 } else {
5790                         result = osd_add_dot_dotdot_internal(info,
5791                                         dir->oo_inode, parent_dir, dot_fid,
5792                                         dot_dot_fid, oth);
5793                 }
5794
5795                 if (result == 0)
5796                         dir->oo_compat_dotdot_created = 1;
5797         }
5798
5799         return result;
5800 }
5801
5802
5803 /**
5804  * It will call the appropriate osd_add* function and return the
5805  * value, return by respective functions.
5806  */
5807 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
5808                           struct inode *cinode, const char *name,
5809                           const struct lu_fid *fid, struct thandle *th)
5810 {
5811         struct osd_thread_info *info = osd_oti_get(env);
5812         struct htree_lock *hlock;
5813         int rc;
5814
5815         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
5816
5817         if (name[0] == '.' && (name[1] == '\0' ||
5818                                (name[1] == '.' && name[2] == '\0'))) {
5819                 if (hlock != NULL) {
5820                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5821                                            pobj->oo_inode, 0);
5822                 } else {
5823                         down_write(&pobj->oo_ext_idx_sem);
5824                 }
5825
5826                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
5827                                         lu_object_fid(&pobj->oo_dt.do_lu),
5828                                         fid, th);
5829         } else {
5830                 if (hlock != NULL) {
5831                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5832                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
5833                 } else {
5834                         down_write(&pobj->oo_ext_idx_sem);
5835                 }
5836
5837                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
5838                         struct lu_fid *tfid = &info->oti_fid;
5839
5840                         *tfid = *fid;
5841                         tfid->f_ver = ~0;
5842                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
5843                                               tfid, hlock, th);
5844                 } else {
5845                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
5846                                               hlock, th);
5847                 }
5848         }
5849         if (!rc && fid_is_namespace_visible(lu_object_fid(&pobj->oo_dt.do_lu))
5850             && pobj->oo_dirent_count != LU_DIRENT_COUNT_UNSET)
5851                 pobj->oo_dirent_count++;
5852
5853         if (hlock != NULL)
5854                 ldiskfs_htree_unlock(hlock);
5855         else
5856                 up_write(&pobj->oo_ext_idx_sem);
5857
5858         return rc;
5859 }
5860
5861 static int
5862 osd_ldiskfs_consistency_check(struct osd_thread_info *oti,
5863                               struct osd_device *dev,
5864                               const struct lu_fid *fid,
5865                               struct osd_inode_id *id)
5866 {
5867         struct lustre_scrub *scrub = &dev->od_scrub.os_scrub;
5868         struct inode *inode = NULL;
5869         int once = 0;
5870         bool insert;
5871         int rc;
5872
5873         ENTRY;
5874         if (!scrub_needs_check(scrub, fid, id->oii_ino))
5875                 RETURN(0);
5876 again:
5877         rc = osd_oi_lookup(oti, dev, fid, &oti->oti_id, 0);
5878         if (rc == -ENOENT) {
5879                 __u32 gen = id->oii_gen;
5880
5881                 insert = true;
5882                 if (inode != NULL)
5883                         goto trigger;
5884
5885                 inode = osd_iget(oti, dev, id);
5886                 /* The inode has been removed (by race maybe). */
5887                 if (IS_ERR(inode)) {
5888                         rc = PTR_ERR(inode);
5889
5890                         RETURN(rc == -ESTALE ? -ENOENT : rc);
5891                 }
5892
5893                 /* The OI mapping is lost. */
5894                 if (gen != OSD_OII_NOGEN)
5895                         goto trigger;
5896
5897                 /*
5898                  * The inode may has been reused by others, we do not know,
5899                  * leave it to be handled by subsequent osd_fid_lookup().
5900                  */
5901                 GOTO(out, rc = 0);
5902         } else if (rc || osd_id_eq(id, &oti->oti_id)) {
5903                 GOTO(out, rc);
5904         }
5905
5906         insert = false;
5907
5908 trigger:
5909         if (scrub->os_running) {
5910                 if (inode == NULL) {
5911                         inode = osd_iget(oti, dev, id);
5912                         /* The inode has been removed (by race maybe). */
5913                         if (IS_ERR(inode)) {
5914                                 rc = PTR_ERR(inode);
5915
5916                                 RETURN(rc == -ESTALE ? -ENOENT : rc);
5917                         }
5918                 }
5919
5920                 rc = osd_oii_insert(dev, fid, id, insert);
5921                 /*
5922                  * There is race condition between osd_oi_lookup and OI scrub.
5923                  * The OI scrub finished just after osd_oi_lookup() failure.
5924                  * Under such case, it is unnecessary to trigger OI scrub again,
5925                  * but try to call osd_oi_lookup() again.
5926                  */
5927                 if (unlikely(rc == -EAGAIN))
5928                         goto again;
5929
5930                 if (!S_ISDIR(inode->i_mode))
5931                         rc = 0;
5932                 else
5933                         rc = osd_check_lmv(oti, dev, inode);
5934
5935                 GOTO(out, rc);
5936         }
5937
5938         if (dev->od_scrub.os_scrub.os_auto_scrub_interval != AS_NEVER &&
5939             ++once == 1) {
5940                 rc = osd_scrub_start(oti->oti_env, dev, SS_AUTO_PARTIAL |
5941                                      SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT);
5942                 CDEBUG_LIMIT(D_LFSCK | D_CONSOLE | D_WARNING,
5943                              "%s: trigger partial OI scrub for RPC inconsistency, checking FID "DFID"/%u: rc = %d\n",
5944                              osd_dev2name(dev), PFID(fid), id->oii_ino, rc);
5945                 if (rc == 0 || rc == -EALREADY)
5946                         goto again;
5947         }
5948
5949         GOTO(out, rc);
5950
5951 out:
5952         iput(inode);
5953
5954         RETURN(rc);
5955 }
5956
5957 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
5958                                struct osd_device *dev,
5959                                struct lu_fid *fid, __u32 ino)
5960 {
5961         struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
5962         struct osd_idmap_cache *oic = &oti->oti_cache;
5963         struct inode *inode;
5964         int rc;
5965
5966         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
5967         inode = osd_iget(oti, dev, &oic->oic_lid);
5968         if (IS_ERR(inode)) {
5969                 fid_zero(&oic->oic_fid);
5970                 return PTR_ERR(inode);
5971         }
5972
5973         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, loa);
5974         iput(inode);
5975         if (rc != 0)
5976                 fid_zero(&oic->oic_fid);
5977         else
5978                 *fid = oic->oic_fid = loa->loa_lma.lma_self_fid;
5979         return rc;
5980 }
5981
5982 void osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
5983                       struct osd_inode_id *id, const struct lu_fid *fid)
5984 {
5985         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
5986                id->oii_ino, id->oii_gen, info);
5987         info->oti_cache.oic_lid = *id;
5988         info->oti_cache.oic_fid = *fid;
5989         info->oti_cache.oic_dev = osd;
5990 }
5991
5992 /**
5993  * Get parent FID from the linkEA.
5994  *
5995  * For a directory which parent resides on remote MDT, to satisfy the
5996  * local e2fsck, we insert it into the /REMOTE_PARENT_DIR locally. On
5997  * the other hand, to make the lookup(..) on the directory can return
5998  * the real parent FID, we append the real parent FID after its ".."
5999  * name entry in the /REMOTE_PARENT_DIR.
6000  *
6001  * Unfortunately, such PFID-in-dirent cannot be preserved via file-level
6002  * backup. So after the restore, we cannot get the right parent FID from
6003  * its ".." name entry in the /REMOTE_PARENT_DIR. Under such case, since
6004  * we have stored the real parent FID in the directory object's linkEA,
6005  * we can parse the linkEA for the real parent FID.
6006  *
6007  * \param[in] env       pointer to the thread context
6008  * \param[in] obj       pointer to the object to be handled
6009  * \param[out]fid       pointer to the buffer to hold the parent FID
6010  *
6011  * \retval              0 for getting the real parent FID successfully
6012  * \retval              negative error number on failure
6013  */
6014 static int osd_get_pfid_from_linkea(const struct lu_env *env,
6015                                     struct osd_object *obj,
6016                                     struct lu_fid *fid)
6017 {
6018         struct osd_thread_info *oti = osd_oti_get(env);
6019         struct lu_buf *buf = &oti->oti_big_buf;
6020         struct dentry *dentry = &oti->oti_obj_dentry;
6021         struct inode *inode = obj->oo_inode;
6022         struct linkea_data ldata = { NULL };
6023         int rc;
6024
6025         ENTRY;
6026
6027         fid_zero(fid);
6028         if (!S_ISDIR(inode->i_mode))
6029                 RETURN(-EIO);
6030
6031 again:
6032         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6033                              buf->lb_buf, buf->lb_len);
6034         if (rc == -ERANGE) {
6035                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6036                                      NULL, 0);
6037                 if (rc > 0) {
6038                         lu_buf_realloc(buf, rc);
6039                         if (buf->lb_buf == NULL)
6040                                 RETURN(-ENOMEM);
6041
6042                         goto again;
6043                 }
6044         }
6045
6046         if (unlikely(rc == 0))
6047                 RETURN(-ENODATA);
6048
6049         if (rc < 0)
6050                 RETURN(rc);
6051
6052         if (unlikely(buf->lb_buf == NULL)) {
6053                 lu_buf_realloc(buf, rc);
6054                 if (buf->lb_buf == NULL)
6055                         RETURN(-ENOMEM);
6056
6057                 goto again;
6058         }
6059
6060         ldata.ld_buf = buf;
6061         rc = linkea_init_with_rec(&ldata);
6062         if (!rc) {
6063                 linkea_first_entry(&ldata);
6064                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, NULL, fid);
6065         }
6066
6067         RETURN(rc);
6068 }
6069
6070 static int osd_verify_ent_by_linkea(const struct lu_env *env,
6071                                     struct inode *inode,
6072                                     const struct lu_fid *pfid,
6073                                     const char *name, const int namelen)
6074 {
6075         struct osd_thread_info *oti = osd_oti_get(env);
6076         struct lu_buf *buf = &oti->oti_big_buf;
6077         struct dentry *dentry = &oti->oti_obj_dentry;
6078         struct linkea_data ldata = { NULL };
6079         struct lu_name cname = { .ln_name = name,
6080                                  .ln_namelen = namelen };
6081         int rc;
6082
6083         ENTRY;
6084
6085 again:
6086         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6087                              buf->lb_buf, buf->lb_len);
6088         if (rc == -ERANGE)
6089                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK, NULL, 0);
6090
6091         if (rc < 0)
6092                 RETURN(rc);
6093
6094         if (unlikely(rc == 0))
6095                 RETURN(-ENODATA);
6096
6097         if (buf->lb_len < rc) {
6098                 lu_buf_realloc(buf, rc);
6099                 if (buf->lb_buf == NULL)
6100                         RETURN(-ENOMEM);
6101
6102                 goto again;
6103         }
6104
6105         ldata.ld_buf = buf;
6106         rc = linkea_init_with_rec(&ldata);
6107         if (!rc)
6108                 rc = linkea_links_find(&ldata, &cname, pfid);
6109
6110         RETURN(rc);
6111 }
6112
6113 /**
6114  * Calls ->lookup() to find dentry. From dentry get inode and
6115  * read inode's ea to get fid. This is required for  interoperability
6116  * mode (b11826)
6117  *
6118  * \retval   0, on success
6119  * \retval -ve, on error
6120  */
6121 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
6122                              struct dt_rec *rec, const struct dt_key *key)
6123 {
6124         struct inode *dir = obj->oo_inode;
6125         struct dentry *dentry;
6126         struct ldiskfs_dir_entry_2 *de;
6127         struct buffer_head *bh;
6128         struct lu_fid *fid = (struct lu_fid *)rec;
6129         struct htree_lock *hlock = NULL;
6130         struct lu_name ln;
6131         int ino;
6132         int rc;
6133
6134         ENTRY;
6135
6136         LASSERT(dir->i_op != NULL);
6137         LASSERT(dir->i_op->lookup != NULL);
6138
6139         rc = obj_name2lu_name(obj, (char *)key, strlen((char *)key), &ln);
6140         if (rc)
6141                 RETURN(rc);
6142
6143         dentry = osd_child_dentry_get(env, obj, ln.ln_name, ln.ln_namelen);
6144
6145         if (obj->oo_hl_head != NULL) {
6146                 hlock = osd_oti_get(env)->oti_hlock;
6147                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
6148                                    dir, LDISKFS_HLOCK_LOOKUP);
6149         } else {
6150                 down_read(&obj->oo_ext_idx_sem);
6151         }
6152
6153         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
6154         if (!IS_ERR(bh)) {
6155                 struct osd_thread_info *oti = osd_oti_get(env);
6156                 struct osd_inode_id *id = &oti->oti_id;
6157                 struct osd_device *dev = osd_obj2dev(obj);
6158
6159                 ino = le32_to_cpu(de->inode);
6160                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
6161                         brelse(bh);
6162                         rc = osd_fail_fid_lookup(oti, dev, fid, ino);
6163                         GOTO(out, rc);
6164                 }
6165
6166                 rc = osd_get_fid_from_dentry(de, rec);
6167
6168                 /* done with de, release bh */
6169                 brelse(bh);
6170                 if (rc != 0) {
6171                         if (unlikely(is_remote_parent_ino(dev, ino))) {
6172                                 const char *name = (const char *)key;
6173
6174                                 /*
6175                                  * If the parent is on remote MDT, and there
6176                                  * is no FID-in-dirent, then we have to get
6177                                  * the parent FID from the linkEA.
6178                                  */
6179                                 if (likely(strlen(name) == 2 &&
6180                                            name[0] == '.' && name[1] == '.'))
6181                                         rc = osd_get_pfid_from_linkea(env, obj,
6182                                                                       fid);
6183                         } else {
6184                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
6185                         }
6186                 } else {
6187                         osd_id_gen(id, ino, OSD_OII_NOGEN);
6188                 }
6189
6190                 if (rc != 0 || osd_remote_fid(env, dev, fid))
6191                         GOTO(out, rc);
6192
6193                 rc = osd_ldiskfs_consistency_check(oti, dev, fid, id);
6194                 if (rc != -ENOENT) {
6195                         /* Other error should not affect lookup result. */
6196                         rc = 0;
6197
6198                         /* Normal file mapping should be added into OI cache
6199                          * after FID in LMA check, but for local files like
6200                          * hsm_actions, their FIDs are not stored in OI files,
6201                          * see osd_initial_OI_scrub(), and here is the only
6202                          * place to load mapping into OI cache.
6203                          */
6204                         if (!fid_is_namespace_visible(fid))
6205                                 osd_add_oi_cache(osd_oti_get(env),
6206                                                  osd_obj2dev(obj), id, fid);
6207                 }
6208         } else {
6209                 rc = PTR_ERR(bh);
6210         }
6211
6212         GOTO(out, rc);
6213
6214 out:
6215         if (hlock != NULL)
6216                 ldiskfs_htree_unlock(hlock);
6217         else
6218                 up_read(&obj->oo_ext_idx_sem);
6219         if (ln.ln_name != (char *)key)
6220                 kfree(ln.ln_name);
6221         RETURN(rc);
6222 }
6223
6224 static int osd_index_declare_ea_insert(const struct lu_env *env,
6225                                        struct dt_object *dt,
6226                                        const struct dt_rec *rec,
6227                                        const struct dt_key *key,
6228                                        struct thandle *handle)
6229 {
6230         struct osd_thandle *oh;
6231         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
6232         struct dt_insert_rec *rec1 = (struct dt_insert_rec *)rec;
6233         const struct lu_fid *fid = rec1->rec_fid;
6234         int credits, rc = 0;
6235         struct osd_idmap_cache *idc;
6236
6237         ENTRY;
6238
6239         LASSERT(!dt_object_remote(dt));
6240         LASSERT(handle != NULL);
6241         LASSERT(fid != NULL);
6242         LASSERT(rec1->rec_type != 0);
6243
6244         oh = container_of(handle, struct osd_thandle, ot_super);
6245         LASSERT(oh->ot_handle == NULL);
6246
6247         credits = osd_dto_credits_noquota[DTO_INDEX_INSERT];
6248
6249         /*
6250          * we can't call iget() while a transactions is running
6251          * (this can lead to a deadlock), but we need to know
6252          * inum and object type. so we find this information at
6253          * declaration and cache in per-thread info
6254          */
6255         idc = osd_idc_find_or_init(env, osd, fid);
6256         if (IS_ERR(idc))
6257                 RETURN(PTR_ERR(idc));
6258         if (idc->oic_remote) {
6259                 /*
6260                  * a reference to remote inode is represented by an
6261                  * agent inode which we have to create
6262                  */
6263                 credits += osd_dto_credits_noquota[DTO_OBJECT_CREATE];
6264                 credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
6265         }
6266
6267         osd_trans_declare_op(env, oh, OSD_OT_INSERT, credits);
6268
6269         if (osd_dt_obj(dt)->oo_inode != NULL) {
6270                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
6271
6272                 /*
6273                  * We ignore block quota on meta pool (MDTs), so needn't
6274                  * calculate how many blocks will be consumed by this index
6275                  * insert
6276                  */
6277                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
6278                                            i_gid_read(inode),
6279                                            i_projid_read(inode), 0,
6280                                            oh, osd_dt_obj(dt), NULL,
6281                                            OSD_QID_BLK);
6282                 if (rc)
6283                         RETURN(rc);
6284
6285 #ifdef HAVE_PROJECT_QUOTA
6286                 /*
6287                  * Reserve credits for local agent inode to transfer
6288                  * to 0, quota enforcement is ignored in this case.
6289                  */
6290                 if (idc->oic_remote &&
6291                     LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
6292                     i_projid_read(inode) != 0)
6293                         rc = osd_declare_attr_qid(env, osd_dt_obj(dt), oh,
6294                                                   0, i_projid_read(inode),
6295                                                   0, false, PRJQUOTA);
6296 #endif
6297         }
6298
6299         RETURN(rc);
6300 }
6301
6302 /**
6303  * Index add function for interoperability mode (b11826).
6304  * It will add the directory entry.This entry is needed to
6305  * maintain name->fid mapping.
6306  *
6307  * \param key it is key i.e. file entry to be inserted
6308  * \param rec it is value of given key i.e. fid
6309  *
6310  * \retval   0, on success
6311  * \retval -ve, on error
6312  */
6313 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
6314                                const struct dt_rec *rec,
6315                                const struct dt_key *key, struct thandle *th)
6316 {
6317         struct osd_object *obj = osd_dt_obj(dt);
6318         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
6319         struct dt_insert_rec *rec1 = (struct dt_insert_rec *)rec;
6320         const struct lu_fid *fid = rec1->rec_fid;
6321         const char *name = (const char *)key;
6322         struct osd_thread_info *oti = osd_oti_get(env);
6323         struct inode *child_inode = NULL;
6324         struct osd_idmap_cache *idc;
6325         int rc;
6326
6327         ENTRY;
6328
6329         if (!dt_object_exists(dt))
6330                 RETURN(-ENOENT);
6331
6332         LASSERT(osd_invariant(obj));
6333         LASSERT(!dt_object_remote(dt));
6334         LASSERT(th != NULL);
6335
6336         osd_trans_exec_op(env, th, OSD_OT_INSERT);
6337
6338         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!\n", PFID(fid));
6339
6340         idc = osd_idc_find(env, osd, fid);
6341         if (unlikely(idc == NULL)) {
6342                 idc = osd_idc_find_or_init(env, osd, fid);
6343                 if (IS_ERR(idc)) {
6344                         /*
6345                          * this dt_insert() wasn't declared properly, so
6346                          * FID is missing in OI cache. we better do not
6347                          * lookup FID in FLDB/OI and don't risk to deadlock,
6348                          * but in some special cases (lfsck testing, etc)
6349                          * it's much simpler than fixing a caller.
6350                          *
6351                          * normally this error should be placed after the first
6352                          * find, but migrate may attach source stripes to
6353                          * target, which doesn't create stripes.
6354                          */
6355                         CERROR("%s: "DFID" wasn't declared for insert\n",
6356                                osd_name(osd), PFID(fid));
6357                         dump_stack();
6358                         RETURN(PTR_ERR(idc));
6359                 }
6360         }
6361
6362         if (idc->oic_remote) {
6363                 /* Insert remote entry */
6364                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
6365                         child_inode =
6366                         igrab(osd->od_mdt_map->omm_remote_parent->d_inode);
6367                 } else {
6368                         child_inode = osd_create_local_agent_inode(env, osd,
6369                                         obj, fid, rec1->rec_type & S_IFMT, th);
6370                         if (IS_ERR(child_inode))
6371                                 RETURN(PTR_ERR(child_inode));
6372                 }
6373         } else {
6374                 /* Insert local entry */
6375                 if (unlikely(idc->oic_lid.oii_ino == 0)) {
6376                         /* for a reason OI cache wasn't filled properly */
6377                         CERROR("%s: OIC for "DFID" isn't filled\n",
6378                                osd_name(osd), PFID(fid));
6379                         RETURN(-EINVAL);
6380                 }
6381                 child_inode = oti->oti_inode;
6382                 if (unlikely(child_inode == NULL)) {
6383                         struct ldiskfs_inode_info *lii;
6384
6385                         OBD_ALLOC_PTR(lii);
6386                         if (lii == NULL)
6387                                 RETURN(-ENOMEM);
6388                         child_inode = oti->oti_inode = &lii->vfs_inode;
6389                 }
6390                 child_inode->i_sb = osd_sb(osd);
6391                 child_inode->i_ino = idc->oic_lid.oii_ino;
6392                 child_inode->i_mode = rec1->rec_type & S_IFMT;
6393         }
6394
6395         rc = osd_ea_add_rec(env, obj, child_inode, name, fid, th);
6396
6397         CDEBUG(D_INODE, "parent %lu insert %s:%lu rc = %d\n",
6398                obj->oo_inode->i_ino, name, child_inode->i_ino, rc);
6399
6400         if (child_inode && child_inode != oti->oti_inode)
6401                 iput(child_inode);
6402         LASSERT(osd_invariant(obj));
6403         osd_trans_exec_check(env, th, OSD_OT_INSERT);
6404
6405         RETURN(rc);
6406 }
6407
6408 /**
6409  *  Initialize osd Iterator for given osd index object.
6410  *
6411  *  \param  dt      osd index object
6412  */
6413
6414 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
6415                                      struct dt_object *dt,
6416                                      __u32 unused)
6417 {
6418         struct osd_it_iam *it;
6419         struct osd_object *obj = osd_dt_obj(dt);
6420         struct lu_object *lo = &dt->do_lu;
6421         struct iam_path_descr *ipd;
6422         struct iam_container *bag = &obj->oo_dir->od_container;
6423
6424         if (!dt_object_exists(dt))
6425                 return ERR_PTR(-ENOENT);
6426
6427         OBD_ALLOC_PTR(it);
6428         if (it == NULL)
6429                 return ERR_PTR(-ENOMEM);
6430
6431         ipd = osd_it_ipd_get(env, bag);
6432         if (likely(ipd != NULL)) {
6433                 it->oi_obj = obj;
6434                 it->oi_ipd = ipd;
6435                 lu_object_get(lo);
6436                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
6437                 return (struct dt_it *)it;
6438         } else {
6439                 OBD_FREE_PTR(it);
6440                 return ERR_PTR(-ENOMEM);
6441         }
6442 }
6443
6444 /**
6445  * free given Iterator.
6446  */
6447 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
6448 {
6449         struct osd_it_iam *it  = (struct osd_it_iam *)di;
6450         struct osd_object *obj = it->oi_obj;
6451
6452         iam_it_fini(&it->oi_it);
6453         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
6454         osd_object_put(env, obj);
6455         OBD_FREE_PTR(it);
6456 }
6457
6458 /**
6459  *  Move Iterator to record specified by \a key
6460  *
6461  *  \param  di      osd iterator
6462  *  \param  key     key for index
6463  *
6464  *  \retval +ve  di points to record with least key not larger than key
6465  *  \retval  0   di points to exact matched key
6466  *  \retval -ve  failure
6467  */
6468
6469 static int osd_it_iam_get(const struct lu_env *env,
6470                           struct dt_it *di, const struct dt_key *key)
6471 {
6472         struct osd_thread_info *oti = osd_oti_get(env);
6473         struct osd_it_iam *it = (struct osd_it_iam *)di;
6474
6475         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
6476                 /* swab quota uid/gid */
6477                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
6478                 key = (struct dt_key *)&oti->oti_quota_id;
6479         }
6480
6481         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
6482 }
6483
6484 /**
6485  *  Release Iterator
6486  *
6487  *  \param  di      osd iterator
6488  */
6489 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
6490 {
6491         struct osd_it_iam *it = (struct osd_it_iam *)di;
6492
6493         iam_it_put(&it->oi_it);
6494 }
6495
6496 /**
6497  *  Move iterator by one record
6498  *
6499  *  \param  di      osd iterator
6500  *
6501  *  \retval +1   end of container reached
6502  *  \retval  0   success
6503  *  \retval -ve  failure
6504  */
6505
6506 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
6507 {
6508         struct osd_it_iam *it = (struct osd_it_iam *)di;
6509
6510         return iam_it_next(&it->oi_it);
6511 }
6512
6513 /**
6514  * Return pointer to the key under iterator.
6515  */
6516
6517 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
6518                                      const struct dt_it *di)
6519 {
6520         struct osd_thread_info *oti = osd_oti_get(env);
6521         struct osd_it_iam *it = (struct osd_it_iam *)di;
6522         struct osd_object *obj = it->oi_obj;
6523         struct dt_key *key;
6524
6525         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
6526
6527         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
6528                 /* swab quota uid/gid */
6529                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
6530                 key = (struct dt_key *)&oti->oti_quota_id;
6531         }
6532
6533         return key;
6534 }
6535
6536 /**
6537  * Return size of key under iterator (in bytes)
6538  */
6539
6540 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
6541 {
6542         struct osd_it_iam *it = (struct osd_it_iam *)di;
6543
6544         return iam_it_key_size(&it->oi_it);
6545 }
6546
6547 static inline void
6548 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
6549 {
6550         /* check if file type is required */
6551         if (ent->lde_attrs & LUDA_TYPE) {
6552                 struct luda_type *lt;
6553                 int align = sizeof(*lt) - 1;
6554
6555                 len = (len + align) & ~align;
6556                 lt = (struct luda_type *)(ent->lde_name + len);
6557                 lt->lt_type = cpu_to_le16(DTTOIF(type));
6558         }
6559
6560         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
6561 }
6562
6563 /**
6564  * build lu direct from backend fs dirent.
6565  */
6566
6567 static inline void
6568 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
6569                    char *name, __u16 namelen, __u16 type, __u32 attr)
6570 {
6571         ent->lde_attrs = attr | LUDA_FID;
6572         fid_cpu_to_le(&ent->lde_fid, fid);
6573
6574         ent->lde_hash = cpu_to_le64(offset);
6575         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
6576
6577         strncpy(ent->lde_name, name, namelen);
6578         ent->lde_name[namelen] = '\0';
6579         ent->lde_namelen = cpu_to_le16(namelen);
6580
6581         /* append lustre attributes */
6582         osd_it_append_attrs(ent, namelen, type);
6583 }
6584
6585 /**
6586  * Return pointer to the record under iterator.
6587  */
6588 static int osd_it_iam_rec(const struct lu_env *env,
6589                           const struct dt_it *di,
6590                           struct dt_rec *dtrec, __u32 attr)
6591 {
6592         struct osd_it_iam *it = (struct osd_it_iam *)di;
6593         struct osd_thread_info *info = osd_oti_get(env);
6594
6595         ENTRY;
6596
6597         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
6598                 const struct osd_fid_pack *rec;
6599                 struct lu_fid *fid = &info->oti_fid;
6600                 struct lu_dirent *lde = (struct lu_dirent *)dtrec;
6601                 char *name;
6602                 int namelen;
6603                 __u64 hash;
6604                 int rc;
6605
6606                 name = (char *)iam_it_key_get(&it->oi_it);
6607                 if (IS_ERR(name))
6608                         RETURN(PTR_ERR(name));
6609
6610                 namelen = iam_it_key_size(&it->oi_it);
6611
6612                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
6613                 if (IS_ERR(rec))
6614                         RETURN(PTR_ERR(rec));
6615
6616                 rc = osd_fid_unpack(fid, rec);
6617                 if (rc)
6618                         RETURN(rc);
6619
6620                 hash = iam_it_store(&it->oi_it);
6621
6622                 /* IAM does not store object type in IAM index (dir) */
6623                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
6624                                    0, LUDA_FID);
6625         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
6626                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
6627                            (struct iam_rec *)dtrec);
6628                 osd_quota_unpack(it->oi_obj, dtrec);
6629         } else {
6630                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
6631                            (struct iam_rec *)dtrec);
6632         }
6633
6634         RETURN(0);
6635 }
6636
6637 /**
6638  * Returns cookie for current Iterator position.
6639  */
6640 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
6641 {
6642         struct osd_it_iam *it = (struct osd_it_iam *)di;
6643
6644         return iam_it_store(&it->oi_it);
6645 }
6646
6647 /**
6648  * Restore iterator from cookie.
6649  *
6650  * \param  di      osd iterator
6651  * \param  hash    Iterator location cookie
6652  *
6653  * \retval +ve  di points to record with least key not larger than key.
6654  * \retval  0   di points to exact matched key
6655  * \retval -ve  failure
6656  */
6657
6658 static int osd_it_iam_load(const struct lu_env *env,
6659                            const struct dt_it *di, __u64 hash)
6660 {
6661         struct osd_it_iam *it = (struct osd_it_iam *)di;
6662
6663         return iam_it_load(&it->oi_it, hash);
6664 }
6665
6666 static const struct dt_index_operations osd_index_iam_ops = {
6667         .dio_lookup         = osd_index_iam_lookup,
6668         .dio_declare_insert = osd_index_declare_iam_insert,
6669         .dio_insert         = osd_index_iam_insert,
6670         .dio_declare_delete = osd_index_declare_iam_delete,
6671         .dio_delete         = osd_index_iam_delete,
6672         .dio_it     = {
6673                 .init     = osd_it_iam_init,
6674                 .fini     = osd_it_iam_fini,
6675                 .get      = osd_it_iam_get,
6676                 .put      = osd_it_iam_put,
6677                 .next     = osd_it_iam_next,
6678                 .key      = osd_it_iam_key,
6679                 .key_size = osd_it_iam_key_size,
6680                 .rec      = osd_it_iam_rec,
6681                 .store    = osd_it_iam_store,
6682                 .load     = osd_it_iam_load
6683         }
6684 };
6685
6686 struct osd_it_ea *osd_it_dir_init(const struct lu_env *env,
6687                                   struct inode *inode, __u32 attr)
6688 {
6689         struct osd_thread_info *info = osd_oti_get(env);
6690         struct osd_it_ea *oie;
6691         struct file *file;
6692         struct dentry *obj_dentry;
6693
6694         ENTRY;
6695
6696         OBD_SLAB_ALLOC_PTR_GFP(oie, osd_itea_cachep, GFP_NOFS);
6697         if (oie == NULL)
6698                 RETURN(ERR_PTR(-ENOMEM));
6699         obj_dentry = &oie->oie_dentry;
6700
6701         obj_dentry->d_inode = inode;
6702         obj_dentry->d_sb = inode->i_sb;
6703         obj_dentry->d_name.hash = 0;
6704
6705         oie->oie_rd_dirent       = 0;
6706         oie->oie_it_dirent       = 0;
6707         oie->oie_dirent          = NULL;
6708         if (unlikely(!info->oti_it_ea_buf_used)) {
6709                 oie->oie_buf = info->oti_it_ea_buf;
6710                 info->oti_it_ea_buf_used = 1;
6711         } else {
6712                 OBD_ALLOC(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6713                 if (oie->oie_buf == NULL)
6714                         RETURN(ERR_PTR(-ENOMEM));
6715         }
6716         oie->oie_obj = NULL;
6717
6718         file = &oie->oie_file;
6719
6720         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
6721         if (attr & LUDA_64BITHASH)
6722                 file->f_mode    = FMODE_64BITHASH;
6723         else
6724                 file->f_mode    = FMODE_32BITHASH;
6725         file->f_path.dentry     = obj_dentry;
6726         file->f_mapping         = inode->i_mapping;
6727         file->f_op              = inode->i_fop;
6728         file->f_inode = inode;
6729
6730         RETURN(oie);
6731 }
6732
6733 /**
6734  * Creates or initializes iterator context.
6735  *
6736  * \retval struct osd_it_ea, iterator structure on success
6737  *
6738  */
6739 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
6740                                     struct dt_object *dt,
6741                                     __u32 attr)
6742 {
6743         struct osd_object *obj = osd_dt_obj(dt);
6744         struct lu_object *lo = &dt->do_lu;
6745         struct osd_it_ea *oie;
6746
6747         ENTRY;
6748
6749         if (!dt_object_exists(dt) || obj->oo_destroyed)
6750                 RETURN(ERR_PTR(-ENOENT));
6751
6752         oie = osd_it_dir_init(env, obj->oo_inode, attr);
6753         if (IS_ERR(oie))
6754                 RETURN((struct dt_it *)oie);
6755
6756         oie->oie_obj = obj;
6757         lu_object_get(lo);
6758         RETURN((struct dt_it *)oie);
6759 }
6760
6761 void osd_it_dir_fini(const struct lu_env *env, struct osd_it_ea *oie,
6762                      struct inode *inode)
6763 {
6764         struct osd_thread_info *info = osd_oti_get(env);
6765
6766         ENTRY;
6767         oie->oie_file.f_op->release(inode, &oie->oie_file);
6768         if (unlikely(oie->oie_buf != info->oti_it_ea_buf))
6769                 OBD_FREE(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6770         else
6771                 info->oti_it_ea_buf_used = 0;
6772         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
6773         EXIT;
6774 }
6775
6776 /**
6777  * Destroy or finishes iterator context.
6778  *
6779  * \param di iterator structure to be destroyed
6780  */
6781 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
6782 {
6783         struct osd_it_ea *oie = (struct osd_it_ea *)di;
6784         struct osd_object *obj = oie->oie_obj;
6785         struct inode *inode = obj->oo_inode;
6786
6787         ENTRY;
6788         osd_it_dir_fini(env, (struct osd_it_ea *)di, inode);
6789         osd_object_put(env, obj);
6790         EXIT;
6791 }
6792
6793 /**
6794  * It position the iterator at given key, so that next lookup continues from
6795  * that key Or it is similar to dio_it->load() but based on a key,
6796  * rather than file position.
6797  *
6798  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
6799  * to the beginning.
6800  *
6801  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
6802  */
6803 static int osd_it_ea_get(const struct lu_env *env,
6804                          struct dt_it *di, const struct dt_key *key)
6805 {
6806         struct osd_it_ea *it = (struct osd_it_ea *)di;
6807
6808         ENTRY;
6809         LASSERT(((const char *)key)[0] == '\0');
6810         it->oie_file.f_pos = 0;
6811         it->oie_rd_dirent = 0;
6812         it->oie_it_dirent = 0;
6813         it->oie_dirent = NULL;
6814
6815         RETURN(+1);
6816 }
6817
6818 /**
6819  * Does nothing
6820  */
6821 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
6822 {
6823 }
6824
6825 struct osd_filldir_cbs {
6826         struct dir_context ctx;
6827         struct osd_it_ea  *it;
6828 };
6829 /**
6830  * It is called internally by ->iterate*(). It fills the
6831  * iterator's in-memory data structure with required
6832  * information i.e. name, namelen, rec_size etc.
6833  *
6834  * \param buf in which information to be filled in.
6835  * \param name name of the file in given dir
6836  *
6837  * \retval 0 on success
6838  * \retval 1 on buffer full
6839  */
6840 #ifdef HAVE_FILLDIR_USE_CTX
6841 static int osd_ldiskfs_filldir(struct dir_context *buf,
6842 #else
6843 static int osd_ldiskfs_filldir(void *buf,
6844 #endif
6845                                const char *name, int namelen,
6846                                loff_t offset, __u64 ino, unsigned int d_type)
6847 {
6848         struct osd_it_ea *it = ((struct osd_filldir_cbs *)buf)->it;
6849         struct osd_object *obj = it->oie_obj;
6850         struct osd_it_ea_dirent *ent = it->oie_dirent;
6851         struct lu_fid *fid = &ent->oied_fid;
6852         struct osd_fid_pack *rec;
6853         struct lu_fid namefid;
6854
6855         ENTRY;
6856
6857 /* this should never happen */
6858         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
6859                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
6860                 RETURN(-EIO);
6861         }
6862
6863         if ((void *)ent - it->oie_buf + sizeof(*ent) + namelen >
6864             OSD_IT_EA_BUFSIZE)
6865                 RETURN(1);
6866
6867         fid_zero(&namefid);
6868
6869         /* "." is just the object itself. */
6870         if (namelen == 1 && name[0] == '.') {
6871                 if (obj != NULL)
6872                         *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
6873         } else if (d_type & LDISKFS_DIRENT_LUFID) {
6874                 rec = (struct osd_fid_pack *)(name + namelen + 1);
6875                 if (osd_fid_unpack(fid, rec) != 0)
6876                         fid_zero(fid);
6877         } else {
6878                 fid_zero(fid);
6879         }
6880         d_type &= ~LDISKFS_DIRENT_LUFID;
6881
6882         /* NOT export local root. */
6883         if (obj != NULL &&
6884             unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
6885                 ino = obj->oo_inode->i_ino;
6886                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
6887         }
6888
6889         if (name[0] == '[')
6890                 sscanf(name + 1, SFID, RFID(&namefid));
6891         if (fid_is_sane(&namefid) || name_is_dot_or_dotdot(name, namelen) ||
6892             !obj || !(obj->oo_lma_flags & LUSTRE_ENCRYPT_FL)) {
6893                 memcpy(ent->oied_name, name, namelen);
6894         } else {
6895                 int presented_len = critical_chars(name, namelen);
6896
6897                 if (presented_len == namelen)
6898                         memcpy(ent->oied_name, name, namelen);
6899                 else
6900                         namelen = critical_encode(name, namelen,
6901                                                   ent->oied_name);
6902
6903                 ent->oied_name[namelen] = '\0';
6904         }
6905
6906         ent->oied_ino     = ino;
6907         ent->oied_off     = offset;
6908         ent->oied_namelen = namelen;
6909         ent->oied_type    = d_type;
6910
6911         it->oie_rd_dirent++;
6912         it->oie_dirent = (void *)ent + cfs_size_round(sizeof(*ent) + namelen);
6913         RETURN(0);
6914 }
6915
6916 /**
6917  * Calls ->iterate*() to load a directory entry at a time
6918  * and stored it in iterator's in-memory data structure.
6919  *
6920  * \param di iterator's in memory structure
6921  *
6922  * \retval   0 on success
6923  * \retval -ve on error
6924  * \retval +1 reach the end of entry
6925  */
6926 int osd_ldiskfs_it_fill(const struct lu_env *env, const struct dt_it *di)
6927 {
6928         struct osd_it_ea *it = (struct osd_it_ea *)di;
6929         struct osd_object *obj = it->oie_obj;
6930         struct htree_lock *hlock = NULL;
6931         struct file *filp = &it->oie_file;
6932         int rc = 0;
6933         struct osd_filldir_cbs buf = {
6934                 .ctx.actor = osd_ldiskfs_filldir,
6935                 .it = it
6936         };
6937
6938         ENTRY;
6939         it->oie_dirent = it->oie_buf;
6940         it->oie_rd_dirent = 0;
6941
6942         if (obj) {
6943                 if (obj->oo_hl_head != NULL) {
6944                         hlock = osd_oti_get(env)->oti_hlock;
6945                         ldiskfs_htree_lock(hlock, obj->oo_hl_head,
6946                                            obj->oo_inode,
6947                                            LDISKFS_HLOCK_READDIR);
6948                 } else {
6949                         down_read(&obj->oo_ext_idx_sem);
6950                 }
6951         }
6952
6953         filp->f_cred = current_cred();
6954         rc = osd_security_file_alloc(filp);
6955         if (rc)
6956                 GOTO(unlock, rc);
6957
6958         filp->f_flags |= O_NOATIME;
6959         filp->f_mode |= FMODE_NONOTIFY;
6960         rc = iterate_dir(filp, &buf.ctx);
6961         if (rc)
6962                 GOTO(unlock, rc);
6963
6964         if (it->oie_rd_dirent == 0) {
6965                 /*
6966                  * If it does not get any dirent, it means it has been reached
6967                  * to the end of the dir
6968                  */
6969                 it->oie_file.f_pos = ldiskfs_get_htree_eof(&it->oie_file);
6970                 if (rc == 0)
6971                         rc = 1;
6972         } else {
6973                 it->oie_dirent = it->oie_buf;
6974                 it->oie_it_dirent = 1;
6975         }
6976 unlock:
6977         if (obj) {
6978                 if (hlock != NULL)
6979                         ldiskfs_htree_unlock(hlock);
6980                 else
6981                         up_read(&obj->oo_ext_idx_sem);
6982         }
6983
6984         RETURN(rc);
6985 }
6986
6987 /**
6988  * It calls osd_ldiskfs_it_fill() which will use ->iterate*()
6989  * to load a directory entry at a time and stored it in
6990  * iterator's in-memory data structure.
6991  *
6992  * \param di iterator's in memory structure
6993  *
6994  * \retval +ve iterator reached to end
6995  * \retval   0 iterator not reached to end
6996  * \retval -ve on error
6997  */
6998 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
6999 {
7000         struct osd_it_ea *it = (struct osd_it_ea *)di;
7001         int rc;
7002
7003         ENTRY;
7004
7005         if (it->oie_it_dirent < it->oie_rd_dirent) {
7006                 it->oie_dirent =
7007                         (void *)it->oie_dirent +
7008                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
7009                                        it->oie_dirent->oied_namelen);
7010                 it->oie_it_dirent++;
7011                 rc = 0;
7012         } else {
7013                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
7014                         rc = 1;
7015                 else
7016                         rc = osd_ldiskfs_it_fill(env, di);
7017         }
7018
7019         RETURN(rc);
7020 }
7021
7022 /**
7023  * Returns the key at current position from iterator's in memory structure.
7024  *
7025  * \param di iterator's in memory structure
7026  *
7027  * \retval key i.e. struct dt_key on success
7028  */
7029 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
7030                                     const struct dt_it *di)
7031 {
7032         struct osd_it_ea *it = (struct osd_it_ea *)di;
7033
7034         return (struct dt_key *)it->oie_dirent->oied_name;
7035 }
7036
7037 /**
7038  * Returns key's size at current position from iterator's in memory structure.
7039  *
7040  * \param di iterator's in memory structure
7041  *
7042  * \retval key_size i.e. struct dt_key on success
7043  */
7044 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
7045 {
7046         struct osd_it_ea *it = (struct osd_it_ea *)di;
7047
7048         return it->oie_dirent->oied_namelen;
7049 }
7050
7051 #if defined LDISKFS_DIR_ENTRY_LEN && defined LDISKFS_DIR_ENTRY_LEN_
7052 #undef LDISKFS_DIR_REC_LEN
7053 #define LDISKFS_DIR_REC_LEN(de)         LDISKFS_DIR_ENTRY_LEN_((de))
7054 #endif
7055
7056 static inline bool osd_dotdot_has_space(struct ldiskfs_dir_entry_2 *de)
7057 {
7058         if (LDISKFS_DIR_REC_LEN(de) >=
7059             __LDISKFS_DIR_REC_LEN(2 + 1 + sizeof(struct osd_fid_pack)))
7060                 return true;
7061
7062         return false;
7063 }
7064
7065 static inline bool
7066 osd_dirent_has_space(struct ldiskfs_dir_entry_2 *de, __u16 namelen,
7067                      unsigned int blocksize, bool dotdot)
7068 {
7069         if (dotdot)
7070                 return osd_dotdot_has_space(de);
7071
7072         if (ldiskfs_rec_len_from_disk(de->rec_len, blocksize) >=
7073             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
7074                 return true;
7075
7076         return false;
7077 }
7078
7079 static int
7080 osd_dirent_reinsert(const struct lu_env *env, struct osd_device *dev,
7081                     handle_t *jh, struct dentry *dentry,
7082                     const struct lu_fid *fid, struct buffer_head *bh,
7083                     struct ldiskfs_dir_entry_2 *de, struct htree_lock *hlock,
7084                     bool dotdot)
7085 {
7086         struct inode *dir = dentry->d_parent->d_inode;
7087         struct inode *inode = dentry->d_inode;
7088         struct osd_fid_pack *rec;
7089         struct ldiskfs_dentry_param *ldp;
7090         int namelen = dentry->d_name.len;
7091         int rc;
7092         struct osd_thread_info *info = osd_oti_get(env);
7093
7094         ENTRY;
7095
7096         if (!ldiskfs_has_feature_dirdata(inode->i_sb))
7097                 RETURN(0);
7098
7099         /* There is enough space to hold the FID-in-dirent. */
7100         if (osd_dirent_has_space(de, namelen, dir->i_sb->s_blocksize, dotdot)) {
7101                 rc = ldiskfs_journal_get_write_access(jh, bh);
7102                 if (rc != 0)
7103                         RETURN(rc);
7104
7105                 de->name[namelen] = 0;
7106                 rec = (struct osd_fid_pack *)(de->name + namelen + 1);
7107                 rec->fp_len = sizeof(struct lu_fid) + 1;
7108                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
7109                 de->file_type |= LDISKFS_DIRENT_LUFID;
7110                 rc = ldiskfs_handle_dirty_metadata(jh, NULL, bh);
7111
7112                 RETURN(rc);
7113         }
7114
7115         LASSERT(!dotdot);
7116
7117         rc = ldiskfs_delete_entry(jh, dir, de, bh);
7118         if (rc != 0)
7119                 RETURN(rc);
7120
7121         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
7122         osd_get_ldiskfs_dirent_param(ldp, fid);
7123         dentry->d_fsdata = (void *)ldp;
7124         dquot_initialize(dir);
7125         rc = osd_ldiskfs_add_entry(info, dev, jh, dentry, inode, hlock);
7126         /*
7127          * It is too bad, we cannot reinsert the name entry back.
7128          * That means we lose it!
7129          */
7130         if (rc != 0)
7131                 CDEBUG(D_LFSCK,
7132                        "%s: fail to reinsert the dirent, dir = %lu/%u, name = %.*s, "DFID": rc = %d\n",
7133                        osd_ino2name(inode), dir->i_ino, dir->i_generation,
7134                        namelen, dentry->d_name.name, PFID(fid), rc);
7135
7136         RETURN(rc);
7137 }
7138
7139 static int
7140 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
7141                         struct osd_it_ea *it, struct lu_fid *fid,
7142                         struct osd_inode_id *id, __u32 *attr)
7143 {
7144         struct osd_thread_info *info = osd_oti_get(env);
7145         struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
7146         struct osd_device *dev = osd_obj2dev(obj);
7147         struct super_block *sb = osd_sb(dev);
7148         const char *devname = osd_name(dev);
7149         struct osd_it_ea_dirent *ent = it->oie_dirent;
7150         struct inode *dir = obj->oo_inode;
7151         struct htree_lock *hlock = NULL;
7152         struct buffer_head *bh = NULL;
7153         handle_t *jh = NULL;
7154         struct ldiskfs_dir_entry_2 *de;
7155         struct dentry *dentry;
7156         struct inode *inode;
7157         const struct lu_fid *pfid = lu_object_fid(&obj->oo_dt.do_lu);
7158         int credits;
7159         int rc;
7160         bool dotdot = false;
7161         bool dirty = false;
7162         struct lu_name ln;
7163
7164         ENTRY;
7165
7166         if (ent->oied_name[0] == '.') {
7167                 if (ent->oied_namelen == 1)
7168                         RETURN(0);
7169
7170                 if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
7171                         dotdot = true;
7172         }
7173
7174         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
7175         inode = osd_iget(info, dev, id);
7176         if (IS_ERR(inode)) {
7177                 rc = PTR_ERR(inode);
7178                 if (rc == -ENOENT || rc == -ESTALE) {
7179                         /*
7180                          * Maybe dangling name entry, or
7181                          * corrupted directory entry.
7182                          */
7183                         *attr |= LUDA_UNKNOWN;
7184                         rc = 0;
7185                 } else {
7186                         CDEBUG(D_LFSCK, "%s: fail to iget() for dirent "
7187                                "check_repair, dir = %lu/%u, name = %.*s, "
7188                                "ino = %llu, rc = %d\n",
7189                                devname, dir->i_ino, dir->i_generation,
7190                                ent->oied_namelen, ent->oied_name,
7191                                ent->oied_ino, rc);
7192                 }
7193
7194                 RETURN(rc);
7195         }
7196
7197         rc = obj_name2lu_name(obj, ent->oied_name, ent->oied_namelen, &ln);
7198         if (rc)
7199                 RETURN(rc);
7200
7201         dentry = osd_child_dentry_by_inode(env, dir, ln.ln_name, ln.ln_namelen);
7202         rc = osd_get_lma(info, inode, dentry, &info->oti_ost_attrs);
7203         if (rc == -ENODATA || !fid_is_sane(&lma->lma_self_fid))
7204                 lma = NULL;
7205         else if (rc != 0)
7206                 GOTO(out, rc);
7207
7208         /*
7209          * We need to ensure that the name entry is still valid.
7210          * Because it may be removed or renamed by other already.
7211          *
7212          * The unlink or rename operation will start journal before PDO lock,
7213          * so to avoid deadlock, here we need to start journal handle before
7214          * related PDO lock also. But because we do not know whether there
7215          * will be something to be repaired before PDO lock, we just start
7216          * journal without conditions.
7217          *
7218          * We may need to remove the name entry firstly, then insert back.
7219          * One credit is for user quota file update.
7220          * One credit is for group quota file update.
7221          * Two credits are for dirty inode.
7222          */
7223         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
7224                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
7225
7226         if (dev->od_dirent_journal != 0) {
7227
7228 again:
7229                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
7230                 if (IS_ERR(jh)) {
7231                         rc = PTR_ERR(jh);
7232                         CDEBUG(D_LFSCK, "%s: fail to start trans for dirent "
7233                                "check_repair, dir = %lu/%u, credits = %d, "
7234                                "name = %.*s, ino = %llu: rc = %d\n",
7235                                devname, dir->i_ino, dir->i_generation, credits,
7236                                ent->oied_namelen, ent->oied_name,
7237                                ent->oied_ino, rc);
7238
7239                         GOTO(out_inode, rc);
7240                 }
7241
7242                 if (obj->oo_hl_head != NULL) {
7243                         hlock = osd_oti_get(env)->oti_hlock;
7244                         /*
7245                          * "0" means exclusive lock for the whole directory.
7246                          * We need to prevent others access such name entry
7247                          * during the delete + insert. Neither HLOCK_ADD nor
7248                          * HLOCK_DEL cannot guarantee the atomicity.
7249                          */
7250                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
7251                 } else {
7252                         down_write(&obj->oo_ext_idx_sem);
7253                 }
7254         } else {
7255                 if (obj->oo_hl_head != NULL) {
7256                         hlock = osd_oti_get(env)->oti_hlock;
7257                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
7258                                            LDISKFS_HLOCK_LOOKUP);
7259                 } else {
7260                         down_read(&obj->oo_ext_idx_sem);
7261                 }
7262         }
7263
7264         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
7265         if (IS_ERR(bh) || le32_to_cpu(de->inode) != inode->i_ino) {
7266                 *attr |= LUDA_IGNORE;
7267
7268                 GOTO(out, rc = 0);
7269         }
7270
7271         /*
7272          * For dotdot entry, if there is not enough space to hold the
7273          * FID-in-dirent, just keep them there. It only happens when the
7274          * device upgraded from 1.8 or restored from MDT file-level backup.
7275          * For the whole directory, only dotdot entry have no FID-in-dirent
7276          * and needs to get FID from LMA when readdir, it will not affect the
7277          * performance much.
7278          */
7279         if (dotdot && !osd_dotdot_has_space(de)) {
7280                 *attr |= LUDA_UNKNOWN;
7281
7282                 GOTO(out, rc = 0);
7283         }
7284
7285         if (lma != NULL) {
7286                 if (lu_fid_eq(fid, &lma->lma_self_fid))
7287                         GOTO(out, rc = 0);
7288
7289                 if (unlikely(lma->lma_compat & LMAC_NOT_IN_OI)) {
7290                         struct lu_fid *tfid = &lma->lma_self_fid;
7291
7292                         if (likely(dotdot &&
7293                                    fid_seq(tfid) == FID_SEQ_LOCAL_FILE &&
7294                                    fid_oid(tfid) == REMOTE_PARENT_DIR_OID)) {
7295                                 /*
7296                                  * It must be REMOTE_PARENT_DIR and as the
7297                                  * 'dotdot' entry of remote directory
7298                                  */
7299                                 *attr |= LUDA_IGNORE;
7300                         } else {
7301                                 CDEBUG(D_LFSCK, "%s: expect remote agent "
7302                                        "parent directory, but got %.*s under "
7303                                        "dir = %lu/%u with the FID "DFID"\n",
7304                                        devname, ent->oied_namelen,
7305                                        ent->oied_name, dir->i_ino,
7306                                        dir->i_generation, PFID(tfid));
7307
7308                                 *attr |= LUDA_UNKNOWN;
7309                         }
7310
7311                         GOTO(out, rc = 0);
7312                 }
7313         }
7314
7315         if (!fid_is_zero(fid)) {
7316                 rc = osd_verify_ent_by_linkea(env, inode, pfid, ent->oied_name,
7317                                               ent->oied_namelen);
7318                 if (rc == -ENOENT ||
7319                     (rc == -ENODATA &&
7320                      !(dev->od_scrub.os_scrub.os_file.sf_flags & SF_UPGRADE))) {
7321                         /*
7322                          * linkEA does not recognize the dirent entry,
7323                          * it may because the dirent entry corruption
7324                          * and points to other's inode.
7325                          */
7326                         CDEBUG(D_LFSCK, "%s: the target inode does not "
7327                                "recognize the dirent, dir = %lu/%u, "
7328                                " name = %.*s, ino = %llu, "
7329                                DFID": rc = %d\n", devname, dir->i_ino,
7330                                dir->i_generation, ent->oied_namelen,
7331                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
7332                         *attr |= LUDA_UNKNOWN;
7333
7334                         GOTO(out, rc = 0);
7335                 }
7336
7337                 if (rc && rc != -ENODATA) {
7338                         CDEBUG(D_LFSCK, "%s: fail to verify FID in the dirent, "
7339                                "dir = %lu/%u, name = %.*s, ino = %llu, "
7340                                DFID": rc = %d\n", devname, dir->i_ino,
7341                                dir->i_generation, ent->oied_namelen,
7342                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
7343                         *attr |= LUDA_UNKNOWN;
7344
7345                         GOTO(out, rc = 0);
7346                 }
7347         }
7348
7349         if (lma != NULL) {
7350                 /*
7351                  * linkEA recognizes the dirent entry, the FID-in-LMA is
7352                  * valid, trusted, in spite of fid_is_sane(fid) or not.
7353                  */
7354                 if (*attr & LUDA_VERIFY_DRYRUN) {
7355                         *fid = lma->lma_self_fid;
7356                         *attr |= LUDA_REPAIR;
7357
7358                         GOTO(out, rc = 0);
7359                 }
7360
7361                 if (jh == NULL) {
7362                         brelse(bh);
7363                         dev->od_dirent_journal = 1;
7364                         if (hlock != NULL) {
7365                                 ldiskfs_htree_unlock(hlock);
7366                                 hlock = NULL;
7367                         } else {
7368                                 up_read(&obj->oo_ext_idx_sem);
7369                         }
7370
7371                         goto again;
7372                 }
7373
7374                 *fid = lma->lma_self_fid;
7375                 dirty = true;
7376                 /* Update or append the FID-in-dirent. */
7377                 rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
7378                                          bh, de, hlock, dotdot);
7379                 if (rc == 0)
7380                         *attr |= LUDA_REPAIR;
7381                 else
7382                         CDEBUG(D_LFSCK, "%s: fail to re-insert FID after "
7383                                "the dirent, dir = %lu/%u, name = %.*s, "
7384                                "ino = %llu, "DFID": rc = %d\n",
7385                                devname, dir->i_ino, dir->i_generation,
7386                                ent->oied_namelen, ent->oied_name,
7387                                ent->oied_ino, PFID(fid), rc);
7388         } else {
7389                 /* lma is NULL, trust the FID-in-dirent if it is valid. */
7390                 if (*attr & LUDA_VERIFY_DRYRUN) {
7391                         if (fid_is_sane(fid)) {
7392                                 *attr |= LUDA_REPAIR;
7393                         } else if (dev->od_index == 0) {
7394                                 lu_igif_build(fid, inode->i_ino,
7395                                               inode->i_generation);
7396                                 *attr |= LUDA_UPGRADE;
7397                         }
7398
7399                         GOTO(out, rc = 0);
7400                 }
7401
7402                 if (jh == NULL) {
7403                         brelse(bh);
7404                         dev->od_dirent_journal = 1;
7405                         if (hlock != NULL) {
7406                                 ldiskfs_htree_unlock(hlock);
7407                                 hlock = NULL;
7408                         } else {
7409                                 up_read(&obj->oo_ext_idx_sem);
7410                         }
7411
7412                         goto again;
7413                 }
7414
7415                 dirty = true;
7416                 if (unlikely(fid_is_sane(fid))) {
7417                         /*
7418                          * FID-in-dirent exists, but FID-in-LMA is lost.
7419                          * Trust the FID-in-dirent, and add FID-in-LMA.
7420                          */
7421                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
7422                         if (rc == 0)
7423                                 *attr |= LUDA_REPAIR;
7424                         else
7425                                 CDEBUG(D_LFSCK, "%s: fail to set LMA for "
7426                                        "update dirent, dir = %lu/%u, "
7427                                        "name = %.*s, ino = %llu, "
7428                                        DFID": rc = %d\n",
7429                                        devname, dir->i_ino, dir->i_generation,
7430                                        ent->oied_namelen, ent->oied_name,
7431                                        ent->oied_ino, PFID(fid), rc);
7432                 } else if (dev->od_index == 0) {
7433                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
7434                         /*
7435                          * It is probably IGIF object. Only aappend the
7436                          * FID-in-dirent. OI scrub will process FID-in-LMA.
7437                          */
7438                         rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
7439                                                  bh, de, hlock, dotdot);
7440                         if (rc == 0)
7441                                 *attr |= LUDA_UPGRADE;
7442                         else
7443                                 CDEBUG(D_LFSCK, "%s: fail to append IGIF "
7444                                        "after the dirent, dir = %lu/%u, "
7445                                        "name = %.*s, ino = %llu, "
7446                                        DFID": rc = %d\n",
7447                                        devname, dir->i_ino, dir->i_generation,
7448                                        ent->oied_namelen, ent->oied_name,
7449                                        ent->oied_ino, PFID(fid), rc);
7450                 }
7451         }
7452
7453         GOTO(out, rc);
7454
7455 out:
7456         if (!IS_ERR(bh))
7457                 brelse(bh);
7458         if (hlock != NULL) {
7459                 ldiskfs_htree_unlock(hlock);
7460         } else {
7461                 if (dev->od_dirent_journal != 0)
7462                         up_write(&obj->oo_ext_idx_sem);
7463                 else
7464                         up_read(&obj->oo_ext_idx_sem);
7465         }
7466
7467         if (jh != NULL)
7468                 ldiskfs_journal_stop(jh);
7469
7470 out_inode:
7471         iput(inode);
7472         if (rc >= 0 && !dirty)
7473                 dev->od_dirent_journal = 0;
7474         if (ln.ln_name != ent->oied_name)
7475                 kfree(ln.ln_name);
7476
7477         return rc;
7478 }
7479
7480 /**
7481  * Returns the value at current position from iterator's in memory structure.
7482  *
7483  * \param di struct osd_it_ea, iterator's in memory structure
7484  * \param attr attr requested for dirent.
7485  * \param lde lustre dirent
7486  *
7487  * \retval   0 no error and \param lde has correct lustre dirent.
7488  * \retval -ve on error
7489  */
7490 static inline int osd_it_ea_rec(const struct lu_env *env,
7491                                 const struct dt_it *di,
7492                                 struct dt_rec *dtrec, __u32 attr)
7493 {
7494         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
7495         struct osd_object      *obj   = it->oie_obj;
7496         struct osd_device      *dev   = osd_obj2dev(obj);
7497         struct osd_thread_info *oti   = osd_oti_get(env);
7498         struct osd_inode_id    *id    = &oti->oti_id;
7499         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
7500         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
7501         __u32 ino = it->oie_dirent->oied_ino;
7502         int rc = 0;
7503
7504         ENTRY;
7505
7506         LASSERT(!is_remote_parent_ino(dev, obj->oo_inode->i_ino));
7507
7508         if (attr & LUDA_VERIFY) {
7509                 if (unlikely(is_remote_parent_ino(dev, ino))) {
7510                         attr |= LUDA_IGNORE;
7511                         /*
7512                          * If the parent is on remote MDT, and there
7513                          * is no FID-in-dirent, then we have to get
7514                          * the parent FID from the linkEA.
7515                          */
7516                         if (!fid_is_sane(fid) &&
7517                             it->oie_dirent->oied_namelen == 2 &&
7518                             it->oie_dirent->oied_name[0] == '.' &&
7519                             it->oie_dirent->oied_name[1] == '.')
7520                                 osd_get_pfid_from_linkea(env, obj, fid);
7521                 } else {
7522                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
7523                                                      &attr);
7524                 }
7525
7526                 if (!fid_is_sane(fid))
7527                         attr |= LUDA_UNKNOWN;
7528         } else {
7529                 attr &= ~LU_DIRENT_ATTRS_MASK;
7530                 if (!fid_is_sane(fid)) {
7531                         bool is_dotdot = false;
7532
7533                         if (it->oie_dirent->oied_namelen == 2 &&
7534                             it->oie_dirent->oied_name[0] == '.' &&
7535                             it->oie_dirent->oied_name[1] == '.')
7536                                 is_dotdot = true;
7537                         /*
7538                          * If the parent is on remote MDT, and there
7539                          * is no FID-in-dirent, then we have to get
7540                          * the parent FID from the linkEA.
7541                          */
7542                         if (is_remote_parent_ino(dev, ino) && is_dotdot) {
7543                                 rc = osd_get_pfid_from_linkea(env, obj, fid);
7544                         } else {
7545                                 if (is_dotdot == false &&
7546                                     OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
7547                                         RETURN(-ENOENT);
7548
7549                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
7550                         }
7551                 }
7552         }
7553
7554         /* Pack the entry anyway, at least the offset is right. */
7555         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
7556                            it->oie_dirent->oied_name,
7557                            it->oie_dirent->oied_namelen,
7558                            it->oie_dirent->oied_type, attr);
7559
7560         RETURN(rc > 0 ? 0 : rc);
7561 }
7562
7563 /**
7564  * Returns the record size size at current position.
7565  *
7566  * This function will return record(lu_dirent) size in bytes.
7567  *
7568  * \param[in] env       execution environment
7569  * \param[in] di        iterator's in memory structure
7570  * \param[in] attr      attribute of the entry, only requires LUDA_TYPE to
7571  *                      calculate the lu_dirent size.
7572  *
7573  * \retval      record size(in bytes & in memory) of the current lu_dirent
7574  *              entry.
7575  */
7576 static int osd_it_ea_rec_size(const struct lu_env *env, const struct dt_it *di,
7577                               __u32 attr)
7578 {
7579         struct osd_it_ea *it = (struct osd_it_ea *)di;
7580
7581         return lu_dirent_calc_size(it->oie_dirent->oied_namelen, attr);
7582 }
7583
7584 /**
7585  * Returns a cookie for current position of the iterator head, so that
7586  * user can use this cookie to load/start the iterator next time.
7587  *
7588  * \param di iterator's in memory structure
7589  *
7590  * \retval cookie for current position, on success
7591  */
7592 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
7593 {
7594         struct osd_it_ea *it = (struct osd_it_ea *)di;
7595
7596         return it->oie_dirent->oied_off;
7597 }
7598
7599 /**
7600  * It calls osd_ldiskfs_it_fill() which will use ->iterate*()
7601  * to load a directory entry at a time and stored it i inn,
7602  * in iterator's in-memory data structure.
7603  *
7604  * \param di struct osd_it_ea, iterator's in memory structure
7605  *
7606  * \retval +ve on success
7607  * \retval -ve on error
7608  */
7609 static int osd_it_ea_load(const struct lu_env *env,
7610                           const struct dt_it *di, __u64 hash)
7611 {
7612         struct osd_it_ea *it = (struct osd_it_ea *)di;
7613         int rc;
7614
7615         ENTRY;
7616         it->oie_file.f_pos = hash;
7617
7618         rc =  osd_ldiskfs_it_fill(env, di);
7619         if (rc > 0)
7620                 rc = -ENODATA;
7621
7622         if (rc == 0)
7623                 rc = 1;
7624
7625         RETURN(rc);
7626 }
7627
7628 /**
7629  * Index lookup function for interoperability mode (b11826).
7630  *
7631  * \param key,  key i.e. file name to be searched
7632  *
7633  * \retval +ve, on success
7634  * \retval -ve, on error
7635  */
7636 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
7637                                struct dt_rec *rec, const struct dt_key *key)
7638 {
7639         struct osd_object *obj = osd_dt_obj(dt);
7640         int rc = 0;
7641
7642         ENTRY;
7643
7644         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
7645         LINVRNT(osd_invariant(obj));
7646
7647         rc = osd_ea_lookup_rec(env, obj, rec, key);
7648         if (rc == 0)
7649                 rc = 1;
7650         RETURN(rc);
7651 }
7652
7653 /**
7654  * Index and Iterator operations for interoperability
7655  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
7656  */
7657 static const struct dt_index_operations osd_index_ea_ops = {
7658         .dio_lookup         = osd_index_ea_lookup,
7659         .dio_declare_insert = osd_index_declare_ea_insert,
7660         .dio_insert         = osd_index_ea_insert,
7661         .dio_declare_delete = osd_index_declare_ea_delete,
7662         .dio_delete         = osd_index_ea_delete,
7663         .dio_it     = {
7664                 .init     = osd_it_ea_init,
7665                 .fini     = osd_it_ea_fini,
7666                 .get      = osd_it_ea_get,
7667                 .put      = osd_it_ea_put,
7668                 .next     = osd_it_ea_next,
7669                 .key      = osd_it_ea_key,
7670                 .key_size = osd_it_ea_key_size,
7671                 .rec      = osd_it_ea_rec,
7672                 .rec_size = osd_it_ea_rec_size,
7673                 .store    = osd_it_ea_store,
7674                 .load     = osd_it_ea_load
7675         }
7676 };
7677
7678 static void *osd_key_init(const struct lu_context *ctx,
7679                           struct lu_context_key *key)
7680 {
7681         struct osd_thread_info *info;
7682
7683         OBD_ALLOC_PTR(info);
7684         if (info == NULL)
7685                 return ERR_PTR(-ENOMEM);
7686
7687         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7688         if (info->oti_it_ea_buf == NULL)
7689                 goto out_free_info;
7690
7691         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
7692
7693         info->oti_hlock = ldiskfs_htree_lock_alloc();
7694         if (info->oti_hlock == NULL)
7695                 goto out_free_ea;
7696
7697         return info;
7698
7699 out_free_ea:
7700         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7701 out_free_info:
7702         OBD_FREE_PTR(info);
7703         return ERR_PTR(-ENOMEM);
7704 }
7705
7706 static void osd_key_fini(const struct lu_context *ctx,
7707                          struct lu_context_key *key, void *data)
7708 {
7709         struct osd_thread_info *info = data;
7710         struct ldiskfs_inode_info *lli = LDISKFS_I(info->oti_inode);
7711         struct osd_idmap_cache *idc = info->oti_ins_cache;
7712
7713         if (info->oti_dio_pages) {
7714                 int i;
7715                 for (i = 0; i < PTLRPC_MAX_BRW_PAGES; i++) {
7716                         struct page *page = info->oti_dio_pages[i];
7717                         if (page) {
7718                                 LASSERT(PagePrivate2(page));
7719                                 LASSERT(PageLocked(page));
7720                                 ClearPagePrivate2(page);
7721                                 unlock_page(page);
7722                                 __free_page(page);
7723                         }
7724                 }
7725                 OBD_FREE_PTR_ARRAY_LARGE(info->oti_dio_pages,
7726                                          PTLRPC_MAX_BRW_PAGES);
7727         }
7728
7729         if (info->oti_inode != NULL)
7730                 OBD_FREE_PTR(lli);
7731         if (info->oti_hlock != NULL)
7732                 ldiskfs_htree_lock_free(info->oti_hlock);
7733         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7734         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
7735         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
7736         lu_buf_free(&info->oti_iobuf.dr_lnb_buf);
7737         lu_buf_free(&info->oti_big_buf);
7738         if (idc != NULL) {
7739                 LASSERT(info->oti_ins_cache_size > 0);
7740                 OBD_FREE_PTR_ARRAY(idc, info->oti_ins_cache_size);
7741                 info->oti_ins_cache = NULL;
7742                 info->oti_ins_cache_size = 0;
7743         }
7744         OBD_FREE_PTR(info);
7745 }
7746
7747 static void osd_key_exit(const struct lu_context *ctx,
7748                          struct lu_context_key *key, void *data)
7749 {
7750         struct osd_thread_info *info = data;
7751
7752         LASSERT(info->oti_r_locks == 0);
7753         LASSERT(info->oti_w_locks == 0);
7754         LASSERT(info->oti_txns    == 0);
7755 }
7756
7757 /* type constructor/destructor: osd_type_init, osd_type_fini */
7758 LU_TYPE_INIT_FINI(osd, &osd_key);
7759
7760 struct lu_context_key osd_key = {
7761         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
7762         .lct_init = osd_key_init,
7763         .lct_fini = osd_key_fini,
7764         .lct_exit = osd_key_exit
7765 };
7766
7767
7768 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
7769                            const char *name, struct lu_device *next)
7770 {
7771         struct osd_device *osd = osd_dev(d);
7772
7773         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname)) >=
7774             sizeof(osd->od_svname))
7775                 return -E2BIG;
7776         return osd_procfs_init(osd, name);
7777 }
7778
7779 static int osd_fid_init(const struct lu_env *env, struct osd_device *osd)
7780 {
7781         struct seq_server_site *ss = osd_seq_site(osd);
7782         int rc = 0;
7783
7784         ENTRY;
7785
7786         if (osd->od_is_ost || osd->od_cl_seq != NULL)
7787                 RETURN(0);
7788
7789         if (unlikely(ss == NULL))
7790                 RETURN(-ENODEV);
7791
7792         OBD_ALLOC_PTR(osd->od_cl_seq);
7793         if (osd->od_cl_seq == NULL)
7794                 RETURN(-ENOMEM);
7795
7796         seq_client_init(osd->od_cl_seq, NULL, LUSTRE_SEQ_METADATA,
7797                         osd->od_svname, ss->ss_server_seq);
7798
7799         if (ss->ss_node_id == 0) {
7800                 /*
7801                  * If the OSD on the sequence controller(MDT0), then allocate
7802                  * sequence here, otherwise allocate sequence after connected
7803                  * to MDT0 (see mdt_register_lwp_callback()).
7804                  */
7805                 rc = seq_server_alloc_meta(osd->od_cl_seq->lcs_srv,
7806                                    &osd->od_cl_seq->lcs_space, env);
7807         }
7808
7809         RETURN(rc);
7810 }
7811
7812 static void osd_fid_fini(const struct lu_env *env, struct osd_device *osd)
7813 {
7814         if (osd->od_cl_seq == NULL)
7815                 return;
7816
7817         seq_client_fini(osd->od_cl_seq);
7818         OBD_FREE_PTR(osd->od_cl_seq);
7819         osd->od_cl_seq = NULL;
7820 }
7821
7822 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
7823 {
7824         ENTRY;
7825
7826         /* shutdown quota slave instance associated with the device */
7827         if (o->od_quota_slave_md != NULL) {
7828                 struct qsd_instance *qsd = o->od_quota_slave_md;
7829
7830                 o->od_quota_slave_md = NULL;
7831                 qsd_fini(env, qsd);
7832         }
7833
7834         if (o->od_quota_slave_dt != NULL) {
7835                 struct qsd_instance *qsd = o->od_quota_slave_dt;
7836
7837                 o->od_quota_slave_dt = NULL;
7838                 qsd_fini(env, qsd);
7839         }
7840
7841         osd_fid_fini(env, o);
7842         osd_scrub_cleanup(env, o);
7843
7844         RETURN(0);
7845 }
7846
7847 static void osd_umount(const struct lu_env *env, struct osd_device *o)
7848 {
7849         ENTRY;
7850
7851         if (o->od_mnt != NULL) {
7852                 shrink_dcache_sb(osd_sb(o));
7853                 osd_sync(env, &o->od_dt_dev);
7854                 wait_event(o->od_commit_cb_done,
7855                           !atomic_read(&o->od_commit_cb_in_flight));
7856
7857                 mntput(o->od_mnt);
7858                 o->od_mnt = NULL;
7859         }
7860
7861         EXIT;
7862 }
7863
7864 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
7865 # ifndef LDISKFS_HAS_INCOMPAT_FEATURE
7866 /* Newer kernels provide the ldiskfs_set_feature_largedir() wrapper already,
7867  * which calls ldiskfs_update_dynamic_rev() to update ancient filesystems.
7868  * All ldiskfs filesystems are already v2, so it is a no-op and unnecessary.
7869  * This avoids maintaining patches to export this otherwise-useless function.
7870  */
7871 void ldiskfs_update_dynamic_rev(struct super_block *sb)
7872 {
7873         /* do nothing */
7874 }
7875 # endif
7876 #endif
7877
7878 static int osd_mount(const struct lu_env *env,
7879                      struct osd_device *o, struct lustre_cfg *cfg)
7880 {
7881         const char *name = lustre_cfg_string(cfg, 0);
7882         const char *dev = lustre_cfg_string(cfg, 1);
7883         const char *opts;
7884         unsigned long page, s_flags = 0, lmd_flags = 0;
7885         struct page *__page;
7886         struct file_system_type *type;
7887         char *options = NULL;
7888         const char *str;
7889         struct osd_thread_info *info = osd_oti_get(env);
7890         struct lu_fid *fid = &info->oti_fid;
7891         struct inode *inode;
7892         int rc = 0, force_over_1024tb = 0;
7893
7894         ENTRY;
7895
7896         if (o->od_mnt != NULL)
7897                 RETURN(0);
7898
7899         if (strlen(dev) >= sizeof(o->od_mntdev))
7900                 RETURN(-E2BIG);
7901         strcpy(o->od_mntdev, dev);
7902
7903         str = lustre_cfg_buf(cfg, 2);
7904         sscanf(str, "%lu:%lu", &s_flags, &lmd_flags);
7905
7906         opts = lustre_cfg_string(cfg, 3);
7907 #ifdef __BIG_ENDIAN
7908         if (opts == NULL || strstr(opts, "bigendian_extents") == NULL) {
7909                 CERROR("%s: device %s extents feature is not guaranteed to "
7910                        "work on big-endian systems. Use \"bigendian_extents\" "
7911                        "mount option to override.\n", name, dev);
7912                 RETURN(-EINVAL);
7913         }
7914 #endif
7915 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7916         if (opts != NULL && strstr(opts, "force_over_128tb") != NULL) {
7917                 CWARN("force_over_128tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force option. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
7918         }
7919 #endif
7920 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 1, 53, 0)
7921         if (opts != NULL && strstr(opts, "force_over_256tb") != NULL) {
7922                 CWARN("force_over_256tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force options. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
7923         }
7924 #endif
7925 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
7926         if (opts != NULL && strstr(opts, "force_over_512tb") != NULL) {
7927                 CWARN("force_over_512tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force options. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
7928         }
7929 #endif
7930
7931         if (opts != NULL && strstr(opts, "force_over_1024tb") != NULL)
7932                 force_over_1024tb = 1;
7933
7934         __page = alloc_page(GFP_KERNEL);
7935         if (__page == NULL)
7936                 GOTO(out, rc = -ENOMEM);
7937         page = (unsigned long)page_address(__page);
7938         options = (char *)page;
7939         *options = '\0';
7940         if (opts != NULL) {
7941                 /* strip out the options for back compatiblity */
7942                 static const char * const sout[] = {
7943                         "mballoc",
7944                         "iopen",
7945                         "noiopen",
7946                         "iopen_nopriv",
7947                         "extents",
7948                         "noextents",
7949                         /* strip out option we processed in osd */
7950                         "bigendian_extents",
7951                         "force_over_128tb",
7952                         "force_over_256tb",
7953                         "force_over_512tb",
7954                         "force_over_1024tb",
7955                         "resetoi",
7956                         NULL
7957                 };
7958                 strncat(options, opts, PAGE_SIZE);
7959                 for (rc = 0, str = options; sout[rc]; ) {
7960                         char *op = strstr(str, sout[rc]);
7961
7962                         if (op == NULL) {
7963                                 rc++;
7964                                 str = options;
7965                                 continue;
7966                         }
7967                         if (op == options || *(op - 1) == ',') {
7968                                 str = op + strlen(sout[rc]);
7969                                 if (*str == ',' || *str == '\0') {
7970                                         *str == ',' ? str++ : str;
7971                                         memmove(op, str, strlen(str) + 1);
7972                                 }
7973                         }
7974                         for (str = op; *str != ',' && *str != '\0'; str++)
7975                                 ;
7976                 }
7977         } else {
7978                 strncat(options, "user_xattr,acl", PAGE_SIZE);
7979         }
7980
7981         /* Glom up mount options */
7982         if (*options != '\0')
7983                 strncat(options, ",", PAGE_SIZE);
7984         strncat(options, "no_mbcache,nodelalloc", PAGE_SIZE);
7985
7986         type = get_fs_type("ldiskfs");
7987         if (!type) {
7988                 CERROR("%s: cannot find ldiskfs module\n", name);
7989                 GOTO(out, rc = -ENODEV);
7990         }
7991
7992         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
7993         module_put(type->owner);
7994
7995         if (IS_ERR(o->od_mnt)) {
7996                 rc = PTR_ERR(o->od_mnt);
7997                 o->od_mnt = NULL;
7998                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
7999                 GOTO(out, rc);
8000         }
8001
8002         if (ldiskfs_blocks_count(LDISKFS_SB(osd_sb(o))->s_es) <<
8003                                  osd_sb(o)->s_blocksize_bits > 1024ULL << 40 &&
8004                                  force_over_1024tb == 0) {
8005                 CERROR("%s: device %s LDISKFS has not been tested on filesystems larger than 1024TB and may cause data corruption. Use 'force_over_1024tb' mount option to override.\n",
8006                        name, dev);
8007                 GOTO(out_mnt, rc = -EINVAL);
8008         }
8009
8010         if (lmd_flags & LMD_FLG_DEV_RDONLY) {
8011                 LCONSOLE_WARN("%s: not support dev_rdonly on this device\n",
8012                               name);
8013
8014                 GOTO(out_mnt, rc = -EOPNOTSUPP);
8015         }
8016
8017         if (!ldiskfs_has_feature_journal(o->od_mnt->mnt_sb)) {
8018                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
8019                 GOTO(out_mnt, rc = -EINVAL);
8020         }
8021
8022 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
8023 #ifdef LDISKFS_MOUNT_DIRDATA
8024         if (ldiskfs_has_feature_dirdata(o->od_mnt->mnt_sb))
8025                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
8026         else if (strstr(name, "MDT")) /* don't complain for MGT or OSTs */
8027                 CWARN("%s: device %s was upgraded from Lustre-1.x without "
8028                       "enabling the dirdata feature. If you do not want to "
8029                       "downgrade to Lustre-1.x again, you can enable it via "
8030                       "'tune2fs -O dirdata device'\n", name, dev);
8031 #endif
8032         /* enable large_dir on MDTs to avoid REMOTE_PARENT_DIR overflow,
8033          * and on very large OSTs to avoid object directory overflow */
8034         if (unlikely(!ldiskfs_has_feature_largedir(o->od_mnt->mnt_sb) &&
8035                      !strstr(name, "MGS"))) {
8036                 ldiskfs_set_feature_largedir(o->od_mnt->mnt_sb);
8037                 LCONSOLE_INFO("%s: enabled 'large_dir' feature on device %s\n",
8038                               name, dev);
8039         }
8040 #endif
8041         inode = osd_sb(o)->s_root->d_inode;
8042         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
8043         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
8044         if (rc != 0) {
8045                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
8046                 GOTO(out_mnt, rc);
8047         }
8048
8049         if (lmd_flags & LMD_FLG_NOSCRUB)
8050                 o->od_scrub.os_scrub.os_auto_scrub_interval = AS_NEVER;
8051
8052         if (blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev))) {
8053                 /* do not use pagecache with flash-backed storage */
8054                 o->od_writethrough_cache = 0;
8055                 o->od_read_cache = 0;
8056         }
8057
8058         GOTO(out, rc = 0);
8059
8060 out_mnt:
8061         mntput(o->od_mnt);
8062         o->od_mnt = NULL;
8063
8064 out:
8065         if (__page)
8066                 __free_page(__page);
8067
8068         return rc;
8069 }
8070
8071 static struct lu_device *osd_device_fini(const struct lu_env *env,
8072                                          struct lu_device *d)
8073 {
8074         struct osd_device *o = osd_dev(d);
8075
8076         ENTRY;
8077
8078         osd_index_backup(env, o, false);
8079         osd_shutdown(env, o);
8080         osd_procfs_fini(o);
8081         if (o->od_oi_table != NULL)
8082                 osd_oi_fini(osd_oti_get(env), o);
8083         if (o->od_extent_bytes_percpu)
8084                 free_percpu(o->od_extent_bytes_percpu);
8085         osd_obj_map_fini(o);
8086         osd_umount(env, o);
8087
8088         RETURN(NULL);
8089 }
8090
8091 static int osd_device_init0(const struct lu_env *env,
8092                             struct osd_device *o,
8093                             struct lustre_cfg *cfg)
8094 {
8095         struct lu_device *l = osd2lu_dev(o);
8096         struct osd_thread_info *info;
8097         int cplen = 0;
8098         char *opts = NULL;
8099         bool restored = false;
8100         int rc;
8101
8102         /* if the module was re-loaded, env can loose its keys */
8103         rc = lu_env_refill((struct lu_env *)env);
8104         if (rc)
8105                 GOTO(out, rc);
8106         info = osd_oti_get(env);
8107         LASSERT(info);
8108
8109         l->ld_ops = &osd_lu_ops;
8110         o->od_dt_dev.dd_ops = &osd_dt_ops;
8111
8112         spin_lock_init(&o->od_osfs_lock);
8113         mutex_init(&o->od_otable_mutex);
8114         INIT_LIST_HEAD(&o->od_orphan_list);
8115         INIT_LIST_HEAD(&o->od_index_backup_list);
8116         INIT_LIST_HEAD(&o->od_index_restore_list);
8117         spin_lock_init(&o->od_lock);
8118         o->od_index_backup_policy = LIBP_NONE;
8119         o->od_t10_type = 0;
8120         init_waitqueue_head(&o->od_commit_cb_done);
8121
8122         o->od_read_cache = 1;
8123         o->od_writethrough_cache = 1;
8124         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
8125         o->od_readcache_max_iosize = OSD_READCACHE_MAX_IO_MB << 20;
8126         o->od_writethrough_max_iosize = OSD_WRITECACHE_MAX_IO_MB << 20;
8127         o->od_scrub.os_scrub.os_auto_scrub_interval = AS_DEFAULT;
8128         /* default fallocate to unwritten extents: LU-14326/LU-14333 */
8129         o->od_fallocate_zero_blocks = 0;
8130
8131         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
8132                         sizeof(o->od_svname));
8133         if (cplen >= sizeof(o->od_svname)) {
8134                 rc = -E2BIG;
8135                 GOTO(out, rc);
8136         }
8137
8138         o->od_index_backup_stop = 0;
8139         o->od_index = -1; /* -1 means index is invalid */
8140         rc = server_name2index(o->od_svname, &o->od_index, NULL);
8141         if (rc == LDD_F_SV_TYPE_OST)
8142                 o->od_is_ost = 1;
8143
8144         o->od_full_scrub_ratio = OFSR_DEFAULT;
8145         o->od_full_scrub_threshold_rate = FULL_SCRUB_THRESHOLD_RATE_DEFAULT;
8146         rc = osd_mount(env, o, cfg);
8147         if (rc != 0)
8148                 GOTO(out, rc);
8149
8150         /* Can only check block device after mount */
8151         o->od_nonrotational =
8152                 blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev));
8153
8154         rc = osd_obj_map_init(env, o);
8155         if (rc != 0)
8156                 GOTO(out_mnt, rc);
8157
8158         rc = lu_site_init(&o->od_site, l);
8159         if (rc != 0)
8160                 GOTO(out_compat, rc);
8161         o->od_site.ls_bottom_dev = l;
8162
8163         rc = lu_site_init_finish(&o->od_site);
8164         if (rc != 0)
8165                 GOTO(out_site, rc);
8166
8167         opts = lustre_cfg_string(cfg, 3);
8168         if (opts && strstr(opts, "resetoi"))
8169                 restored = true;
8170
8171         INIT_LIST_HEAD(&o->od_ios_list);
8172         /* setup scrub, including OI files initialization */
8173         o->od_in_init = 1;
8174         rc = osd_scrub_setup(env, o, restored);
8175         o->od_in_init = 0;
8176         if (rc < 0)
8177                 GOTO(out_site, rc);
8178
8179         rc = osd_procfs_init(o, o->od_svname);
8180         if (rc != 0) {
8181                 CERROR("%s: can't initialize procfs: rc = %d\n",
8182                        o->od_svname, rc);
8183                 GOTO(out_scrub, rc);
8184         }
8185
8186         LASSERT(l->ld_site->ls_linkage.next != NULL);
8187         LASSERT(l->ld_site->ls_linkage.prev != NULL);
8188
8189         /* initialize quota slave instance */
8190         /* currently it's no need to prepare qsd_instance_md for OST */
8191         if (!o->od_is_ost) {
8192                 o->od_quota_slave_md = qsd_init(env, o->od_svname,
8193                                                 &o->od_dt_dev,
8194                                                 o->od_proc_entry, true);
8195                 if (IS_ERR(o->od_quota_slave_md)) {
8196                         rc = PTR_ERR(o->od_quota_slave_md);
8197                         o->od_quota_slave_md = NULL;
8198                         GOTO(out_procfs, rc);
8199                 }
8200         }
8201
8202         o->od_quota_slave_dt = qsd_init(env, o->od_svname, &o->od_dt_dev,
8203                                         o->od_proc_entry, false);
8204
8205         if (IS_ERR(o->od_quota_slave_dt)) {
8206                 if (o->od_quota_slave_md != NULL) {
8207                         qsd_fini(env, o->od_quota_slave_md);
8208                         o->od_quota_slave_md = NULL;
8209                 }
8210
8211                 rc = PTR_ERR(o->od_quota_slave_dt);
8212                 o->od_quota_slave_dt = NULL;
8213                 GOTO(out_procfs, rc);
8214         }
8215
8216         o->od_extent_bytes_percpu = alloc_percpu(unsigned int);
8217         if (!o->od_extent_bytes_percpu) {
8218                 rc = -ENOMEM;
8219                 GOTO(out_procfs, rc);
8220         }
8221
8222         RETURN(0);
8223
8224 out_procfs:
8225         osd_procfs_fini(o);
8226 out_scrub:
8227         osd_scrub_cleanup(env, o);
8228 out_site:
8229         lu_site_fini(&o->od_site);
8230 out_compat:
8231         osd_obj_map_fini(o);
8232 out_mnt:
8233         osd_umount(env, o);
8234 out:
8235         return rc;
8236 }
8237
8238 static struct lu_device *osd_device_alloc(const struct lu_env *env,
8239                                           struct lu_device_type *t,
8240                                           struct lustre_cfg *cfg)
8241 {
8242         struct osd_device *o;
8243         int rc;
8244
8245         OBD_ALLOC_PTR(o);
8246         if (o == NULL)
8247                 return ERR_PTR(-ENOMEM);
8248
8249         rc = dt_device_init(&o->od_dt_dev, t);
8250         if (rc == 0) {
8251                 /*
8252                  * Because the ctx might be revived in dt_device_init,
8253                  * refill the env here
8254                  */
8255                 lu_env_refill((struct lu_env *)env);
8256                 rc = osd_device_init0(env, o, cfg);
8257                 if (rc)
8258                         dt_device_fini(&o->od_dt_dev);
8259         }
8260
8261         if (unlikely(rc != 0))
8262                 OBD_FREE_PTR(o);
8263
8264         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
8265 }
8266
8267 static struct lu_device *osd_device_free(const struct lu_env *env,
8268                                          struct lu_device *d)
8269 {
8270         struct osd_device *o = osd_dev(d);
8271
8272         ENTRY;
8273
8274         /* XXX: make osd top device in order to release reference */
8275         d->ld_site->ls_top_dev = d;
8276         lu_site_purge(env, d->ld_site, -1);
8277         lu_site_print(env, d->ld_site, &d->ld_site->ls_obj_hash.nelems,
8278                       D_ERROR, lu_cdebug_printer);
8279         lu_site_fini(&o->od_site);
8280         dt_device_fini(&o->od_dt_dev);
8281         OBD_FREE_PTR(o);
8282         RETURN(NULL);
8283 }
8284
8285 static int osd_process_config(const struct lu_env *env,
8286                               struct lu_device *d, struct lustre_cfg *cfg)
8287 {
8288         struct osd_device *o = osd_dev(d);
8289         ssize_t count;
8290         int rc;
8291
8292         ENTRY;
8293
8294         switch (cfg->lcfg_command) {
8295         case LCFG_SETUP:
8296                 rc = osd_mount(env, o, cfg);
8297                 break;
8298         case LCFG_CLEANUP:
8299                 /*
8300                  * For the case LCFG_PRE_CLEANUP is not called in advance,
8301                  * that may happend if hit failure during mount process.
8302                  */
8303                 osd_index_backup(env, o, false);
8304                 lu_dev_del_linkage(d->ld_site, d);
8305                 rc = osd_shutdown(env, o);
8306                 break;
8307         case LCFG_PARAM:
8308                 LASSERT(&o->od_dt_dev);
8309                 count  = class_modify_config(cfg, PARAM_OSD,
8310                                              &o->od_dt_dev.dd_kobj);
8311                 if (count < 0)
8312                         count = class_modify_config(cfg, PARAM_OST,
8313                                                     &o->od_dt_dev.dd_kobj);
8314                 rc = count > 0 ? 0 : count;
8315                 break;
8316         case LCFG_PRE_CLEANUP:
8317                 osd_scrub_stop(o);
8318                 osd_index_backup(env, o,
8319                                  o->od_index_backup_policy != LIBP_NONE);
8320                 rc = 0;
8321                 break;
8322         default:
8323                 rc = -ENOSYS;
8324         }
8325
8326         RETURN(rc);
8327 }
8328
8329 static int osd_recovery_complete(const struct lu_env *env,
8330                                  struct lu_device *d)
8331 {
8332         struct osd_device *osd = osd_dev(d);
8333         int rc = 0;
8334
8335         ENTRY;
8336
8337         if (osd->od_quota_slave_md == NULL && osd->od_quota_slave_dt == NULL)
8338                 RETURN(0);
8339
8340         /*
8341          * start qsd instance on recovery completion, this notifies the quota
8342          * slave code that we are about to process new requests now
8343          */
8344         rc = qsd_start(env, osd->od_quota_slave_dt);
8345         if (rc == 0 && osd->od_quota_slave_md != NULL)
8346                 rc = qsd_start(env, osd->od_quota_slave_md);
8347
8348         RETURN(rc);
8349 }
8350
8351 /*
8352  * we use exports to track all osd users
8353  */
8354 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
8355                            struct obd_device *obd, struct obd_uuid *cluuid,
8356                            struct obd_connect_data *data, void *localdata)
8357 {
8358         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8359         struct lustre_handle conn;
8360         int rc;
8361
8362         ENTRY;
8363
8364         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
8365
8366         rc = class_connect(&conn, obd, cluuid);
8367         if (rc)
8368                 RETURN(rc);
8369
8370         *exp = class_conn2export(&conn);
8371
8372         spin_lock(&osd->od_osfs_lock);
8373         osd->od_connects++;
8374         spin_unlock(&osd->od_osfs_lock);
8375
8376         RETURN(0);
8377 }
8378
8379 /*
8380  * once last export (we don't count self-export) disappeared
8381  * osd can be released
8382  */
8383 static int osd_obd_disconnect(struct obd_export *exp)
8384 {
8385         struct obd_device *obd = exp->exp_obd;
8386         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8387         int rc, release = 0;
8388
8389         ENTRY;
8390
8391         /* Only disconnect the underlying layers on the final disconnect. */
8392         spin_lock(&osd->od_osfs_lock);
8393         osd->od_connects--;
8394         if (osd->od_connects == 0)
8395                 release = 1;
8396         spin_unlock(&osd->od_osfs_lock);
8397
8398         rc = class_disconnect(exp); /* bz 9811 */
8399
8400         if (rc == 0 && release)
8401                 class_manual_cleanup(obd);
8402         RETURN(rc);
8403 }
8404
8405 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
8406                        struct lu_device *dev)
8407 {
8408         struct osd_device *osd = osd_dev(dev);
8409         struct lr_server_data *lsd =
8410                         &osd->od_dt_dev.dd_lu_dev.ld_site->ls_tgt->lut_lsd;
8411         int result = 0;
8412
8413         ENTRY;
8414
8415         if (osd->od_quota_slave_md != NULL) {
8416                 /* set up quota slave objects for inode */
8417                 result = qsd_prepare(env, osd->od_quota_slave_md);
8418                 if (result != 0)
8419                         RETURN(result);
8420         }
8421
8422         if (osd->od_quota_slave_dt != NULL) {
8423                 /* set up quota slave objects for block */
8424                 result = qsd_prepare(env, osd->od_quota_slave_dt);
8425                 if (result != 0)
8426                         RETURN(result);
8427         }
8428
8429
8430         if (lsd->lsd_feature_incompat & OBD_COMPAT_OST) {
8431 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 52, 0)
8432                 if (lsd->lsd_feature_rocompat & OBD_ROCOMPAT_IDX_IN_IDIF) {
8433                         osd->od_index_in_idif = 1;
8434                 } else {
8435                         osd->od_index_in_idif = 0;
8436                         result = osd_register_proc_index_in_idif(osd);
8437                         if (result != 0)
8438                                 RETURN(result);
8439                 }
8440 #else
8441                 osd->od_index_in_idif = 1;
8442 #endif
8443         }
8444
8445         result = osd_fid_init(env, osd);
8446
8447         RETURN(result);
8448 }
8449
8450 /**
8451  * Implementation of lu_device_operations::ldo_fid_alloc() for OSD
8452  *
8453  * Allocate FID.
8454  *
8455  * see include/lu_object.h for the details.
8456  */
8457 static int osd_fid_alloc(const struct lu_env *env, struct lu_device *d,
8458                          struct lu_fid *fid, struct lu_object *parent,
8459                          const struct lu_name *name)
8460 {
8461         struct osd_device *osd = osd_dev(d);
8462
8463         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
8464 }
8465
8466 static const struct lu_object_operations osd_lu_obj_ops = {
8467         .loo_object_init      = osd_object_init,
8468         .loo_object_delete    = osd_object_delete,
8469         .loo_object_release   = osd_object_release,
8470         .loo_object_free      = osd_object_free,
8471         .loo_object_print     = osd_object_print,
8472         .loo_object_invariant = osd_object_invariant
8473 };
8474
8475 const struct lu_device_operations osd_lu_ops = {
8476         .ldo_object_alloc      = osd_object_alloc,
8477         .ldo_process_config    = osd_process_config,
8478         .ldo_recovery_complete = osd_recovery_complete,
8479         .ldo_prepare           = osd_prepare,
8480         .ldo_fid_alloc         = osd_fid_alloc,
8481 };
8482
8483 static const struct lu_device_type_operations osd_device_type_ops = {
8484         .ldto_init = osd_type_init,
8485         .ldto_fini = osd_type_fini,
8486
8487         .ldto_start = osd_type_start,
8488         .ldto_stop  = osd_type_stop,
8489
8490         .ldto_device_alloc = osd_device_alloc,
8491         .ldto_device_free  = osd_device_free,
8492
8493         .ldto_device_init = osd_device_init,
8494         .ldto_device_fini = osd_device_fini
8495 };
8496
8497 static struct lu_device_type osd_device_type = {
8498         .ldt_tags     = LU_DEVICE_DT,
8499         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
8500         .ldt_ops      = &osd_device_type_ops,
8501         .ldt_ctx_tags = LCT_LOCAL,
8502 };
8503
8504 static int osd_health_check(const struct lu_env *env, struct obd_device *obd)
8505 {
8506         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8507         struct super_block *sb = osd_sb(osd);
8508
8509         return (osd->od_mnt == NULL || sb->s_flags & SB_RDONLY);
8510 }
8511
8512 /*
8513  * lprocfs legacy support.
8514  */
8515 static const struct obd_ops osd_obd_device_ops = {
8516         .o_owner = THIS_MODULE,
8517         .o_connect      = osd_obd_connect,
8518         .o_disconnect   = osd_obd_disconnect,
8519         .o_health_check = osd_health_check,
8520 };
8521
8522 static ssize_t track_declares_assert_show(struct kobject *kobj,
8523                                    struct attribute *attr,
8524                                    char *buf)
8525 {
8526         return sprintf(buf, "%d\n", ldiskfs_track_declares_assert);
8527 }
8528
8529 static ssize_t track_declares_assert_store(struct kobject *kobj,
8530                                            struct attribute *attr,
8531                                            const char *buffer, size_t count)
8532 {
8533         bool track_declares_assert;
8534         int rc;
8535
8536         rc = kstrtobool(buffer, &track_declares_assert);
8537         if (rc)
8538                 return rc;
8539
8540         ldiskfs_track_declares_assert = track_declares_assert;
8541
8542         return count;
8543 }
8544 LUSTRE_RW_ATTR(track_declares_assert);
8545
8546 static int __init osd_init(void)
8547 {
8548         struct kobject *kobj;
8549         int rc;
8550
8551         BUILD_BUG_ON(BH_DXLock >=
8552                      sizeof(((struct buffer_head *)0)->b_state) * 8);
8553 #if !defined(CONFIG_DEBUG_MUTEXES) && !defined(CONFIG_DEBUG_SPINLOCK)
8554         /* please, try to keep osd_thread_info smaller than a page */
8555         BUILD_BUG_ON(sizeof(struct osd_thread_info) > PAGE_SIZE);
8556 #endif
8557
8558         osd_oi_mod_init();
8559
8560         rc = lu_kmem_init(ldiskfs_caches);
8561         if (rc)
8562                 return rc;
8563
8564 #ifdef CONFIG_KALLSYMS
8565         priv_security_file_alloc =
8566                 (void *)cfs_kallsyms_lookup_name("security_file_alloc");
8567 #endif
8568
8569         rc = class_register_type(&osd_obd_device_ops, NULL, true,
8570                                  LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
8571         if (rc) {
8572                 lu_kmem_fini(ldiskfs_caches);
8573                 return rc;
8574         }
8575
8576         kobj = kset_find_obj(lustre_kset, LUSTRE_OSD_LDISKFS_NAME);
8577         if (kobj) {
8578                 rc = sysfs_create_file(kobj,
8579                                        &lustre_attr_track_declares_assert.attr);
8580                 kobject_put(kobj);
8581                 if (rc) {
8582                         CWARN("osd-ldiskfs: track_declares_assert failed to register with sysfs\n");
8583                         rc = 0;
8584                 }
8585         }
8586         return rc;
8587 }
8588
8589 static void __exit osd_exit(void)
8590 {
8591         struct kobject *kobj;
8592
8593         kobj = kset_find_obj(lustre_kset, LUSTRE_OSD_LDISKFS_NAME);
8594         if (kobj) {
8595                 sysfs_remove_file(kobj,
8596                                   &lustre_attr_track_declares_assert.attr);
8597                 kobject_put(kobj);
8598         }
8599         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
8600         lu_kmem_fini(ldiskfs_caches);
8601 }
8602
8603 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
8604 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
8605 MODULE_VERSION(LUSTRE_VERSION_STRING);
8606 MODULE_LICENSE("GPL");
8607
8608 module_init(osd_init);
8609 module_exit(osd_exit);