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