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