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