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