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