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