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