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