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