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