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