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