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