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