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