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