Whamcloud - gitweb
LU-16380 osd-ldiskfs: race in OI mapping
[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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/osd/osd_handler.c
32  *
33  * Top-level entry points into osd module
34  *
35  * Author: Nikita Danilov <nikita@clusterfs.com>
36  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
37  */
38
39 #define DEBUG_SUBSYSTEM S_OSD
40
41 #include <linux/fs_struct.h>
42 #include <linux/module.h>
43 #include <linux/user_namespace.h>
44 #include <linux/uidgid.h>
45
46 /* prerequisite for linux/xattr.h */
47 #include <linux/types.h>
48 /* prerequisite for linux/xattr.h */
49 #include <linux/fs.h>
50 /* XATTR_{REPLACE,CREATE} */
51 #include <linux/xattr.h>
52
53 #include <ldiskfs/ldiskfs.h>
54 #include <ldiskfs/xattr.h>
55 #include <ldiskfs/ldiskfs_extents.h>
56 #undef ENTRY
57 /*
58  * struct OBD_{ALLOC,FREE}*()
59  * OBD_FAIL_CHECK
60  */
61 #include <obd_support.h>
62 /* struct ptlrpc_thread */
63 #include <lustre_net.h>
64 #include <lustre_fid.h>
65 /* process_config */
66 #include <uapi/linux/lustre/lustre_param.h>
67
68 #include "osd_internal.h"
69 #include "osd_dynlocks.h"
70
71 /* llo_* api support */
72 #include <md_object.h>
73 #include <lustre_quota.h>
74
75 #include <lustre_linkea.h>
76
77 /* encoding routines */
78 #include <lustre_crypto.h>
79
80 /* Maximum EA size is limited by LNET_MTU for remote objects */
81 #define OSD_MAX_EA_SIZE 1048364
82
83 int ldiskfs_pdo = 1;
84 module_param(ldiskfs_pdo, int, 0644);
85 MODULE_PARM_DESC(ldiskfs_pdo, "ldiskfs with parallel directory operations");
86
87 int ldiskfs_track_declares_assert;
88 module_param(ldiskfs_track_declares_assert, int, 0644);
89 MODULE_PARM_DESC(ldiskfs_track_declares_assert, "LBUG during tracking of declares");
90
91 /* Slab to allocate dynlocks */
92 struct kmem_cache *dynlock_cachep;
93
94 /* Slab to allocate osd_it_ea */
95 struct kmem_cache *osd_itea_cachep;
96
97 static struct lu_kmem_descr ldiskfs_caches[] = {
98         {
99                 .ckd_cache = &dynlock_cachep,
100                 .ckd_name  = "dynlock_cache",
101                 .ckd_size  = sizeof(struct dynlock_handle)
102         },
103         {
104                 .ckd_cache = &osd_itea_cachep,
105                 .ckd_name  = "osd_itea_cache",
106                 .ckd_size  = sizeof(struct osd_it_ea)
107         },
108         {
109                 .ckd_cache = NULL
110         }
111 };
112
113 static const char dot[] = ".";
114 static const char dotdot[] = "..";
115
116 static const struct lu_object_operations      osd_lu_obj_ops;
117 static const struct dt_object_operations      osd_obj_ops;
118 static const struct dt_object_operations      osd_obj_otable_it_ops;
119 static const struct dt_index_operations       osd_index_iam_ops;
120 static const struct dt_index_operations       osd_index_ea_ops;
121
122 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
123                           const struct lu_fid *fid);
124 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
125                                                 struct osd_device *osd);
126 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
127                          const struct lu_buf *buf, const char *name, int fl,
128                          struct thandle *handle);
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 static int osd_is_write_locked(const struct lu_env *env, struct osd_object *o)
158 {
159         struct osd_thread_info *oti = osd_oti_get(env);
160
161         return oti->oti_w_locks > 0 && o->oo_owner == env;
162 }
163
164 /*
165  * Concurrency: doesn't access mutable data
166  */
167 static int osd_root_get(const struct lu_env *env,
168                         struct dt_device *dev, struct lu_fid *f)
169 {
170         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
171         return 0;
172 }
173
174 /*
175  * the following set of functions are used to maintain per-thread
176  * cache of FID->ino mapping. this mechanism is needed to resolve
177  * FID to inode at dt_insert() which in turn stores ino in the
178  * directory entries to keep ldiskfs compatible with ext[34].
179  * due to locking-originated restrictions we can't lookup ino
180  * using LU cache (deadlock is possible). lookup using OI is quite
181  * expensive. so instead we maintain this cache and methods like
182  * dt_create() fill it. so in the majority of cases dt_insert() is
183  * able to find needed mapping in lockless manner.
184  */
185 static struct osd_idmap_cache *
186 osd_idc_find(const struct lu_env *env, struct osd_device *osd,
187              const struct lu_fid *fid)
188 {
189         struct osd_thread_info *oti = osd_oti_get(env);
190         struct osd_idmap_cache *idc = oti->oti_ins_cache;
191         int i;
192
193         for (i = 0; i < oti->oti_ins_cache_used; i++) {
194                 if (!lu_fid_eq(&idc[i].oic_fid, fid))
195                         continue;
196                 if (idc[i].oic_dev != osd)
197                         continue;
198
199                 return idc + i;
200         }
201
202         return NULL;
203 }
204
205 static struct osd_idmap_cache *
206 osd_idc_add(const struct lu_env *env, struct osd_device *osd,
207             const struct lu_fid *fid)
208 {
209         struct osd_thread_info *oti   = osd_oti_get(env);
210         struct osd_idmap_cache *idc;
211         int i;
212
213         if (unlikely(oti->oti_ins_cache_used >= oti->oti_ins_cache_size)) {
214                 i = oti->oti_ins_cache_size * 2;
215                 if (i == 0)
216                         i = OSD_INS_CACHE_SIZE;
217                 OBD_ALLOC_PTR_ARRAY_LARGE(idc, i);
218                 if (idc == NULL)
219                         return ERR_PTR(-ENOMEM);
220                 if (oti->oti_ins_cache != NULL) {
221                         memcpy(idc, oti->oti_ins_cache,
222                                oti->oti_ins_cache_used * sizeof(*idc));
223                         OBD_FREE_PTR_ARRAY_LARGE(oti->oti_ins_cache,
224                                            oti->oti_ins_cache_used);
225                 }
226                 oti->oti_ins_cache = idc;
227                 oti->oti_ins_cache_size = i;
228         }
229
230         idc = oti->oti_ins_cache + oti->oti_ins_cache_used++;
231         idc->oic_fid = *fid;
232         idc->oic_dev = osd;
233         idc->oic_lid.oii_ino = 0;
234         idc->oic_lid.oii_gen = 0;
235         idc->oic_remote = 0;
236
237         return idc;
238 }
239
240 /*
241  * lookup mapping for the given fid in the cache, initialize a
242  * new one if not found. the initialization checks whether the
243  * object is local or remote. for local objects, OI is used to
244  * learn ino/generation. the function is used when the caller
245  * has no information about the object, e.g. at dt_insert().
246  */
247 static struct osd_idmap_cache *
248 osd_idc_find_or_init(const struct lu_env *env, struct osd_device *osd,
249                      const struct lu_fid *fid)
250 {
251         struct osd_idmap_cache *idc;
252         int rc;
253
254         idc = osd_idc_find(env, osd, fid);
255         LASSERT(!IS_ERR(idc));
256         if (idc != NULL)
257                 return idc;
258
259         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
260                osd->od_svname, PFID(fid));
261
262         /* new mapping is needed */
263         idc = osd_idc_add(env, osd, fid);
264         if (IS_ERR(idc)) {
265                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
266                        osd->od_svname, PFID(fid), PTR_ERR(idc));
267                 return idc;
268         }
269
270         /* initialize it */
271         rc = osd_remote_fid(env, osd, fid);
272         if (unlikely(rc < 0))
273                 return ERR_PTR(rc);
274
275         if (rc == 0) {
276                 /* the object is local, lookup in OI */
277                 /* XXX: probably cheaper to lookup in LU first? */
278                 rc = osd_oi_lookup(osd_oti_get(env), osd, fid,
279                                    &idc->oic_lid, 0);
280                 if (unlikely(rc < 0)) {
281                         CERROR("can't lookup: rc = %d\n", rc);
282                         return ERR_PTR(rc);
283                 }
284         } else {
285                 /* the object is remote */
286                 idc->oic_remote = 1;
287         }
288
289         return idc;
290 }
291
292 static void osd_idc_dump_lma(const struct lu_env *env,
293                                 struct osd_device *osd,
294                                 unsigned long ino,
295                                 bool check_in_oi)
296 {
297         struct osd_thread_info *info = osd_oti_get(env);
298         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
299         const struct lu_fid *fid;
300         struct osd_inode_id lid;
301         struct inode *inode;
302         int rc;
303
304         inode = osd_ldiskfs_iget(osd_sb(osd), ino);
305         if (IS_ERR(inode)) {
306                 CERROR("%s: can't get inode %lu: rc = %d\n",
307                        osd->od_svname, ino, (int)PTR_ERR(inode));
308                 return;
309         }
310         if (is_bad_inode(inode)) {
311                 CERROR("%s: bad inode %lu\n", osd->od_svname, ino);
312                 goto put;
313         }
314         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
315         if (rc) {
316                 CERROR("%s: can't get LMA for %lu: rc = %d\n",
317                        osd->od_svname, ino, rc);
318                 goto put;
319         }
320         fid = &loa->loa_lma.lma_self_fid;
321         LCONSOLE(D_INFO, "%s: "DFID" in inode %lu/%u\n", osd->od_svname,
322                       PFID(fid), ino, (unsigned)inode->i_generation);
323         if (!check_in_oi)
324                 goto put;
325         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
326         if (rc) {
327                 CERROR("%s: can't lookup "DFID": rc = %d\n",
328                        osd->od_svname, PFID(fid), rc);
329                 goto put;
330         }
331         LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n", osd->od_svname,
332                       PFID(fid), lid.oii_ino, lid.oii_gen);
333 put:
334         iput(inode);
335 }
336
337 static void osd_idc_dump_debug(const struct lu_env *env,
338                                 struct osd_device *osd,
339                                 const struct lu_fid *fid,
340                                 unsigned long ino1,
341                                 unsigned long ino2)
342 {
343         struct osd_inode_id lid;
344
345         int rc;
346
347         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
348         if (!rc) {
349                 LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n",
350                         osd->od_svname, PFID(fid), lid.oii_ino, lid.oii_gen);
351                 osd_idc_dump_lma(env, osd, lid.oii_ino, false);
352         } else {
353                 CERROR("%s: can't lookup "DFID": rc = %d\n",
354                        osd->od_svname, PFID(fid), rc);
355         }
356         if (ino1)
357                 osd_idc_dump_lma(env, osd, ino1, true);
358         if (ino2)
359                 osd_idc_dump_lma(env, osd, ino2, true);
360 }
361
362 /*
363  * lookup mapping for given FID and fill it from the given object.
364  * the object is lolcal by definition.
365  */
366 static int osd_idc_find_and_init(const struct lu_env *env,
367                                  struct osd_device *osd,
368                                  struct osd_object *obj)
369 {
370         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
371         struct osd_idmap_cache *idc;
372
373         idc = osd_idc_find(env, osd, fid);
374         LASSERT(!IS_ERR(idc));
375         if (idc != NULL) {
376                 if (obj->oo_inode == NULL)
377                         return 0;
378                 if (idc->oic_lid.oii_ino != obj->oo_inode->i_ino) {
379                         if (idc->oic_lid.oii_ino) {
380                                 osd_idc_dump_debug(env, osd, fid,
381                                                    idc->oic_lid.oii_ino,
382                                                    obj->oo_inode->i_ino);
383                                 return -EINVAL;
384                         }
385                         idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
386                         idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
387                 }
388                 return 0;
389         }
390
391         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
392                osd->od_svname, PFID(fid));
393
394         /* new mapping is needed */
395         idc = osd_idc_add(env, osd, fid);
396         if (IS_ERR(idc)) {
397                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
398                        osd->od_svname, PFID(fid), PTR_ERR(idc));
399                 return PTR_ERR(idc);
400         }
401
402         if (obj->oo_inode != NULL) {
403                 idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
404                 idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
405         }
406         return 0;
407 }
408
409 /*
410  * OSD object methods.
411  */
412
413 /*
414  * Concurrency: no concurrent access is possible that early in object
415  * life-cycle.
416  */
417 static struct lu_object *osd_object_alloc(const struct lu_env *env,
418                                           const struct lu_object_header *hdr,
419                                           struct lu_device *d)
420 {
421         struct osd_object *mo;
422
423         OBD_ALLOC_PTR(mo);
424         if (mo != NULL) {
425                 struct lu_object *l;
426                 struct lu_object_header *h;
427                 struct osd_device *o = osd_dev(d);
428
429                 l = &mo->oo_dt.do_lu;
430                 if (unlikely(o->od_in_init)) {
431                         OBD_ALLOC_PTR(h);
432                         if (!h) {
433                                 OBD_FREE_PTR(mo);
434                                 return NULL;
435                         }
436
437                         lu_object_header_init(h);
438                         lu_object_init(l, h, d);
439                         lu_object_add_top(h, l);
440                         mo->oo_header = h;
441                 } else {
442                         dt_object_init(&mo->oo_dt, NULL, d);
443                         mo->oo_header = NULL;
444                 }
445
446                 mo->oo_dt.do_ops = &osd_obj_ops;
447                 l->lo_ops = &osd_lu_obj_ops;
448                 init_rwsem(&mo->oo_sem);
449                 init_rwsem(&mo->oo_ext_idx_sem);
450                 spin_lock_init(&mo->oo_guard);
451                 INIT_LIST_HEAD(&mo->oo_xattr_list);
452                 return l;
453         }
454         return NULL;
455 }
456
457 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
458                 struct dentry *dentry, struct lustre_ost_attrs *loa)
459 {
460         int rc;
461
462         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
463                              (void *)loa, sizeof(*loa));
464         if (rc > 0) {
465                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
466
467                 if (rc < sizeof(*lma))
468                         return -EINVAL;
469
470                 rc = 0;
471                 lustre_loa_swab(loa, true);
472                 /* Check LMA compatibility */
473                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
474                         rc = -EOPNOTSUPP;
475                         CWARN("%s: unsupported incompat LMA feature(s) %#x for fid = "DFID", ino = %lu: rc = %d\n",
476                               osd_ino2name(inode),
477                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
478                               PFID(&lma->lma_self_fid), inode->i_ino, rc);
479                 }
480         } else if (rc == 0) {
481                 rc = -ENODATA;
482         }
483
484         return rc;
485 }
486
487 /*
488  * retrieve object from backend ext fs.
489  **/
490 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
491                        struct osd_inode_id *id)
492 {
493         int rc;
494         struct inode *inode = NULL;
495
496         /*
497          * if we look for an inode withing a running
498          * transaction, then we risk to deadlock
499          * osd_dirent_check_repair() breaks this
500          */
501          /* LASSERT(current->journal_info == NULL); */
502
503         inode = osd_ldiskfs_iget(osd_sb(dev), id->oii_ino);
504         if (IS_ERR(inode)) {
505                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
506                        id->oii_ino, PTR_ERR(inode));
507         } else if (id->oii_gen != OSD_OII_NOGEN &&
508                    inode->i_generation != id->oii_gen) {
509                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
510                        "i_generation = %u\n",
511                        id->oii_ino, id->oii_gen, inode->i_generation);
512                 iput(inode);
513                 inode = ERR_PTR(-ESTALE);
514         } else if (inode->i_nlink == 0) {
515                 /*
516                  * due to parallel readdir and unlink,
517                  * we can have dead inode here.
518                  */
519                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
520                 iput(inode);
521                 inode = ERR_PTR(-ESTALE);
522         } else if (is_bad_inode(inode)) {
523                 CWARN("%s: bad inode: ino = %u: rc = %d\n",
524                       osd_dev2name(dev), id->oii_ino, -ENOENT);
525                 iput(inode);
526                 inode = ERR_PTR(-ENOENT);
527         } else  if (osd_is_ea_inode(inode)) {
528                 /*
529                  * EA inode is internal ldiskfs object, should don't visible
530                  * on osd
531                  */
532                 CDEBUG(D_INODE, "EA inode: ino = %u\n", id->oii_ino);
533                 iput(inode);
534                 inode = ERR_PTR(-ENOENT);
535         } else if ((rc = osd_attach_jinode(inode))) {
536                 iput(inode);
537                 inode = ERR_PTR(rc);
538         } else {
539                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
540                 if (id->oii_gen == OSD_OII_NOGEN)
541                         osd_id_gen(id, inode->i_ino, inode->i_generation);
542
543                 /*
544                  * Do not update file c/mtime in ldiskfs.
545                  * NB: we don't have any lock to protect this because we don't
546                  * have reference on osd_object now, but contention with
547                  * another lookup + attr_set can't happen in the tiny window
548                  * between if (...) and set S_NOCMTIME.
549                  */
550                 if (!(inode->i_flags & S_NOCMTIME))
551                         inode->i_flags |= S_NOCMTIME;
552         }
553         return inode;
554 }
555
556 int osd_ldiskfs_add_entry(struct osd_thread_info *info, struct osd_device *osd,
557                           handle_t *handle, struct dentry *child,
558                           struct inode *inode, struct htree_lock *hlock)
559 {
560         int rc, rc2;
561
562         rc = __ldiskfs_add_entry(handle, child, inode, hlock);
563         if (rc == -ENOBUFS || rc == -ENOSPC) {
564                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
565                 struct inode *parent = child->d_parent->d_inode;
566                 struct lu_fid *fid = NULL;
567                 char fidstr[FID_LEN + 1] = "unknown";
568
569                 rc2 = osd_get_lma(info, parent, child->d_parent, loa);
570                 if (!rc2) {
571                         fid = &loa->loa_lma.lma_self_fid;
572                 } else if (rc2 == -ENODATA) {
573                         if (unlikely(is_root_inode(parent))) {
574                                 fid = &info->oti_fid3;
575                                 lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
576                         } else if (!osd->od_is_ost && osd->od_index == 0) {
577                                 fid = &info->oti_fid3;
578                                 lu_igif_build(fid, parent->i_ino,
579                                               parent->i_generation);
580                         }
581                 }
582
583                 if (fid != NULL)
584                         snprintf(fidstr, sizeof(fidstr), DFID, PFID(fid));
585
586                 /* below message is checked in sanity.sh test_129 */
587                 if (rc == -ENOSPC) {
588                         CWARN("%s: directory (inode: %lu, FID: %s) has reached max size limit\n",
589                               osd_name(osd), parent->i_ino, fidstr);
590                 } else {
591                         rc = 0; /* ignore such error now */
592                         CWARN("%s: directory (inode: %lu, FID: %s) is approaching max size limit\n",
593                               osd_name(osd), parent->i_ino, fidstr);
594                 }
595
596         }
597
598         return rc;
599 }
600
601
602 struct inode *
603 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
604              struct osd_inode_id *id, struct lu_fid *fid)
605 {
606         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
607         struct inode *inode;
608         int rc;
609
610         inode = osd_iget(info, dev, id);
611         if (IS_ERR(inode))
612                 return inode;
613
614         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
615         if (!rc) {
616                 *fid = loa->loa_lma.lma_self_fid;
617         } else if (rc == -ENODATA) {
618                 if (unlikely(is_root_inode(inode)))
619                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
620                 else
621                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
622         } else {
623                 iput(inode);
624                 inode = ERR_PTR(rc);
625         }
626         return inode;
627 }
628
629 static struct inode *osd_iget_check(struct osd_thread_info *info,
630                                     struct osd_device *dev,
631                                     const struct lu_fid *fid,
632                                     struct osd_inode_id *id,
633                                     bool trusted)
634 {
635         struct inode *inode;
636         int rc = 0;
637
638         ENTRY;
639
640         /*
641          * The cached OI mapping is trustable. If we cannot locate the inode
642          * via the cached OI mapping, then return the failure to the caller
643          * directly without further OI checking.
644          */
645
646 again:
647         inode = osd_iget(info, dev, id);
648         if (IS_ERR(inode)) {
649                 rc = PTR_ERR(inode);
650                 if (!trusted && (rc == -ENOENT || rc == -ESTALE))
651                         goto check_oi;
652
653                 CDEBUG(D_INODE, "no inode for FID: "DFID", ino = %u, rc = %d\n",
654                        PFID(fid), id->oii_ino, rc);
655                 GOTO(put, rc);
656         }
657
658 check_oi:
659         if (rc != 0) {
660                 __u32 saved_ino = id->oii_ino;
661                 __u32 saved_gen = id->oii_gen;
662
663                 LASSERT(!trusted);
664                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
665
666                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
667                 /*
668                  * XXX: There are four possible cases:
669                  *      1. rc = 0.
670                  *         Backup/restore caused the OI invalid.
671                  *      2. rc = 0.
672                  *         Someone unlinked the object but NOT removed
673                  *         the OI mapping, such as mount target device
674                  *         as ldiskfs, and modify something directly.
675                  *      3. rc = -ENOENT.
676                  *         Someone just removed the object between the
677                  *         former oi_lookup and the iget. It is normal.
678                  *      4. Other failure cases.
679                  *
680                  *      Generally, when the device is mounted, it will
681                  *      auto check whether the system is restored from
682                  *      file-level backup or not. We trust such detect
683                  *      to distinguish the 1st case from the 2nd case:
684                  *      if the OI files are consistent but may contain
685                  *      stale OI mappings because of case 2, if iget()
686                  *      returns -ENOENT or -ESTALE, then it should be
687                  *      the case 2.
688                  */
689                 if (rc != 0)
690                         /*
691                          * If the OI mapping was in OI file before the
692                          * osd_iget_check(), but now, it is disappear,
693                          * then it must be removed by race. That is a
694                          * normal race case.
695                          */
696                         GOTO(put, rc);
697
698                 /*
699                  * It is the OI scrub updated the OI mapping by race.
700                  * The new OI mapping must be valid.
701                  */
702                 if (saved_ino != id->oii_ino ||
703                     (saved_gen != id->oii_gen && saved_gen != OSD_OII_NOGEN)) {
704                         if (!IS_ERR(inode))
705                                 iput(inode);
706
707                         trusted = true;
708                         goto again;
709                 }
710
711                 if (IS_ERR(inode)) {
712                         if (dev->od_scrub.os_scrub.os_file.sf_flags &
713                             SF_INCONSISTENT)
714                                 /*
715                                  * It still can be the case 2, but we cannot
716                                  * distinguish it from the case 1. So return
717                                  * -EREMCHG to block current operation until
718                                  *  OI scrub rebuilt the OI mappings.
719                                  */
720                                 rc = -EREMCHG;
721                         else
722                                 rc = -ENOENT;
723
724                         GOTO(put, rc);
725                 }
726
727                 if (inode->i_generation == id->oii_gen)
728                         rc = -ENOENT;
729                 else
730                         rc = -EREMCHG;
731         }
732
733         GOTO(put, rc);
734
735 put:
736         if (rc != 0) {
737                 if (!IS_ERR(inode))
738                         iput(inode);
739
740                 inode = ERR_PTR(rc);
741         }
742
743         return inode;
744 }
745
746 /**
747  * \retval +v: new filter_fid does not contain self-fid
748  * \retval 0:  filter_fid_18_23, contains self-fid
749  * \retval -v: other failure cases
750  */
751 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
752                  struct dentry *dentry, struct lu_fid *fid)
753 {
754         struct filter_fid *ff = &info->oti_ff;
755         struct ost_id *ostid = &info->oti_ostid;
756         int rc;
757
758         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
759         if (rc == sizeof(struct filter_fid_18_23)) {
760                 struct filter_fid_18_23 *ff_old = (void *)ff;
761
762                 ostid_set_seq(ostid, le64_to_cpu(ff_old->ff_seq));
763                 rc = ostid_set_id(ostid, le64_to_cpu(ff_old->ff_objid));
764                 /*
765                  * XXX: use 0 as the index for compatibility, the caller will
766                  * handle index related issues when necessary.
767                  */
768                 if (!rc)
769                         ostid_to_fid(fid, ostid, 0);
770         } else if (rc >= (int)sizeof(struct filter_fid_24_29)) {
771                 rc = 1;
772         } else if (rc >= 0) {
773                 rc = -EINVAL;
774         }
775
776         return rc;
777 }
778
779 static int osd_lma_self_repair(struct osd_thread_info *info,
780                                struct osd_device *osd, struct inode *inode,
781                                const struct lu_fid *fid, __u32 compat)
782 {
783         handle_t *jh;
784         int rc;
785
786         LASSERT(current->journal_info == NULL);
787
788         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
789                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
790         if (IS_ERR(jh)) {
791                 rc = PTR_ERR(jh);
792                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
793                       osd_name(osd), rc);
794                 return rc;
795         }
796
797         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
798         if (rc != 0)
799                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
800                       osd_name(osd), rc);
801         ldiskfs_journal_stop(jh);
802         return rc;
803 }
804
805 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
806 {
807         struct osd_thread_info *info = osd_oti_get(env);
808         struct osd_device *osd = osd_obj2dev(obj);
809         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
810         struct lustre_mdt_attrs *lma = &loa->loa_lma;
811         struct inode *inode = obj->oo_inode;
812         struct dentry *dentry = &info->oti_obj_dentry;
813         struct lu_fid *fid = NULL;
814         const struct lu_fid *rfid = lu_object_fid(&obj->oo_dt.do_lu);
815         int rc;
816
817         ENTRY;
818
819         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
820                              (void *)loa, sizeof(*loa));
821         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
822                 fid = &lma->lma_self_fid;
823                 rc = osd_get_idif(info, inode, dentry, fid);
824                 if (rc > 0 || (rc == -ENODATA && osd->od_index_in_idif)) {
825                         /*
826                          * For the given OST-object, if it has neither LMA nor
827                          * FID in XATTR_NAME_FID, then the given FID (which is
828                          * contained in the @obj, from client RPC for locating
829                          * the OST-object) is trusted. We use it to generate
830                          * the LMA.
831                          */
832                         osd_lma_self_repair(info, osd, inode, rfid,
833                                             LMAC_FID_ON_OST);
834                         RETURN(0);
835                 }
836         }
837
838         if (rc < 0)
839                 RETURN(rc);
840
841         if (rc > 0) {
842                 rc = 0;
843                 lustre_lma_swab(lma);
844                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
845                              (CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT) &&
846                               S_ISREG(inode->i_mode)))) {
847                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
848                               "fid = "DFID", ino = %lu\n", osd_name(osd),
849                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
850                               PFID(rfid), inode->i_ino);
851                         rc = -EOPNOTSUPP;
852                 } else {
853                         fid = &lma->lma_self_fid;
854                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
855                             osd->od_is_ost)
856                                 obj->oo_pfid_in_lma = 1;
857                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
858                             !osd->od_is_ost)
859                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
860                 }
861         }
862
863         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
864                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
865                         struct ost_id   *oi   = &info->oti_ostid;
866                         struct lu_fid   *fid1 = &info->oti_fid3;
867                         __u32            idx  = fid_idif_ost_idx(rfid);
868
869                         /*
870                          * For old IDIF, the OST index is not part of the IDIF,
871                          * Means that different OSTs may have the same IDIFs.
872                          * Under such case, we need to make some compatible
873                          * check to make sure to trigger OI scrub properly.
874                          */
875                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
876                                 /* Given @rfid is new, LMA is old. */
877                                 fid_to_ostid(fid, oi);
878                                 ostid_to_fid(fid1, oi, idx);
879                                 if (lu_fid_eq(fid1, rfid)) {
880                                         if (osd->od_index_in_idif)
881                                                 osd_lma_self_repair(info, osd,
882                                                         inode, rfid,
883                                                         LMAC_FID_ON_OST);
884                                         RETURN(0);
885                                 }
886                         }
887                 }
888
889                 rc = -EREMCHG;
890         }
891
892         RETURN(rc);
893 }
894
895 struct osd_check_lmv_buf {
896         /* please keep it as first member */
897         struct dir_context ctx;
898         struct osd_thread_info *oclb_info;
899         struct osd_device *oclb_dev;
900         int oclb_items;
901         bool oclb_found;
902 };
903
904 /**
905  * It is called internally by ->iterate*() to filter out the
906  * local slave object's FID of the striped directory.
907  *
908  * \retval      1 found the local slave's FID
909  * \retval      0 continue to check next item
910  * \retval      -ve for failure
911  */
912 #ifdef HAVE_FILLDIR_USE_CTX
913 static int osd_stripe_dir_filldir(struct dir_context *buf,
914 #else
915 static int osd_stripe_dir_filldir(void *buf,
916 #endif
917                                   const char *name, int namelen,
918                                   loff_t offset, __u64 ino, unsigned int d_type)
919 {
920         struct osd_check_lmv_buf *oclb = (struct osd_check_lmv_buf *)buf;
921         struct osd_thread_info *oti = oclb->oclb_info;
922         struct lu_fid *fid = &oti->oti_fid3;
923         struct osd_inode_id *id = &oti->oti_id3;
924         struct osd_device *dev = oclb->oclb_dev;
925         struct inode *inode;
926
927         oclb->oclb_items++;
928
929         if (name[0] == '.')
930                 return 0;
931
932         fid_zero(fid);
933         sscanf(name + 1, SFID, RFID(fid));
934         if (!fid_is_sane(fid))
935                 return 0;
936
937         if (osd_remote_fid(oti->oti_env, dev, fid))
938                 return 0;
939
940         osd_id_gen(id, ino, OSD_OII_NOGEN);
941         inode = osd_iget(oti, dev, id);
942         if (IS_ERR(inode))
943                 return PTR_ERR(inode);
944
945         iput(inode);
946         osd_add_oi_cache(oti, dev, id, fid);
947         osd_scrub_oi_insert(dev, fid, id, true);
948         oclb->oclb_found = true;
949
950         return 1;
951 }
952
953 /*
954  * When lookup item under striped directory, we need to locate the master
955  * MDT-object of the striped directory firstly, then the client will send
956  * lookup (getattr_by_name) RPC to the MDT with some slave MDT-object's FID
957  * and the item's name. If the system is restored from MDT file level backup,
958  * then before the OI scrub completely built the OI files, the OI mappings of
959  * the master MDT-object and slave MDT-object may be invalid. Usually, it is
960  * not a problem for the master MDT-object. Because when locate the master
961  * MDT-object, we will do name based lookup (for the striped directory itself)
962  * firstly, during such process we can setup the correct OI mapping for the
963  * master MDT-object. But it will be trouble for the slave MDT-object. Because
964  * the client will not trigger name based lookup on the MDT to locate the slave
965  * MDT-object before locating item under the striped directory, then when
966  * osd_fid_lookup(), it will find that the OI mapping for the slave MDT-object
967  * is invalid and does not know what the right OI mapping is, then the MDT has
968  * to return -EINPROGRESS to the client to notify that the OI scrub is rebuiding
969  * the OI file, related OI mapping is unknown yet, please try again later. And
970  * then client will re-try the RPC again and again until related OI mapping has
971  * been updated. That is quite inefficient.
972  *
973  * To resolve above trouble, we will handle it as the following two cases:
974  *
975  * 1) The slave MDT-object and the master MDT-object are on different MDTs.
976  *    It is relative easy. Be as one of remote MDT-objects, the slave MDT-object
977  *    is linked under /REMOTE_PARENT_DIR with the name of its FID string.
978  *    We can locate the slave MDT-object via lookup the /REMOTE_PARENT_DIR
979  *    directly. Please check osd_fid_lookup().
980  *
981  * 2) The slave MDT-object and the master MDT-object reside on the same MDT.
982  *    Under such case, during lookup the master MDT-object, we will lookup the
983  *    slave MDT-object via readdir against the master MDT-object, because the
984  *    slave MDT-objects information are stored as sub-directories with the name
985  *    "${FID}:${index}". Then when find the local slave MDT-object, its OI
986  *    mapping will be recorded. Then subsequent osd_fid_lookup() will know
987  *    the correct OI mapping for the slave MDT-object.
988  */
989 static int osd_check_lmv(struct osd_thread_info *oti, struct osd_device *dev,
990                          struct inode *inode)
991 {
992         struct lu_buf *buf = &oti->oti_big_buf;
993         struct file *filp;
994         struct lmv_mds_md_v1 *lmv1;
995         struct osd_check_lmv_buf oclb = {
996                 .ctx.actor = osd_stripe_dir_filldir,
997                 .oclb_info = oti,
998                 .oclb_dev = dev,
999                 .oclb_found = false,
1000         };
1001         int rc = 0;
1002
1003         ENTRY;
1004         /* We should use the VFS layer to create a real dentry. */
1005         oti->oti_obj_dentry.d_inode = inode;
1006         oti->oti_obj_dentry.d_sb = inode->i_sb;
1007
1008         filp = alloc_file_pseudo(inode, dev->od_mnt, "/", O_NOATIME,
1009                                  inode->i_fop);
1010         if (IS_ERR(filp))
1011                 RETURN(-ENOMEM);
1012
1013         filp->f_mode |= FMODE_64BITHASH;
1014         filp->f_pos = 0;
1015         ihold(inode);
1016 again:
1017         rc = __osd_xattr_get(inode, filp->f_path.dentry, XATTR_NAME_LMV,
1018                              buf->lb_buf, buf->lb_len);
1019         if (rc == -ERANGE) {
1020                 rc = __osd_xattr_get(inode, filp->f_path.dentry,
1021                                      XATTR_NAME_LMV, NULL, 0);
1022                 if (rc > 0) {
1023                         lu_buf_realloc(buf, rc);
1024                         if (buf->lb_buf == NULL)
1025                                 GOTO(out, rc = -ENOMEM);
1026
1027                         goto again;
1028                 }
1029         }
1030
1031         if (unlikely(rc == 0 || rc == -ENODATA))
1032                 GOTO(out, rc = 0);
1033
1034         if (rc < 0)
1035                 GOTO(out, rc);
1036
1037         if (unlikely(buf->lb_buf == NULL)) {
1038                 lu_buf_realloc(buf, rc);
1039                 if (buf->lb_buf == NULL)
1040                         GOTO(out, rc = -ENOMEM);
1041
1042                 goto again;
1043         }
1044
1045         lmv1 = buf->lb_buf;
1046         if (le32_to_cpu(lmv1->lmv_magic) != LMV_MAGIC_V1)
1047                 GOTO(out, rc = 0);
1048
1049         do {
1050                 oclb.oclb_items = 0;
1051                 rc = iterate_dir(filp, &oclb.ctx);
1052         } while (rc >= 0 && oclb.oclb_items > 0 && !oclb.oclb_found &&
1053                  filp->f_pos != LDISKFS_HTREE_EOF_64BIT);
1054 out:
1055         fput(filp);
1056         if (rc < 0)
1057                 CDEBUG(D_LFSCK,
1058                        "%s: cannot check LMV, ino = %lu/%u: rc = %d\n",
1059                        osd_ino2name(inode), inode->i_ino, inode->i_generation,
1060                        rc);
1061         else
1062                 rc = 0;
1063
1064         RETURN(rc);
1065 }
1066
1067 /**
1068  * Is object in scrub inconsistent/stale list.
1069  *
1070  * \a scrub has two lists, os_inconsistent_items contains mappings to fix, while
1071  * os_stale_items contains mappings failed to fix.
1072  */
1073 static bool fid_in_scrub_list(struct lustre_scrub *scrub,
1074                               const struct list_head *list,
1075                               const struct lu_fid *fid)
1076 {
1077         struct osd_inconsistent_item *oii;
1078
1079         if (list_empty(list))
1080                 return false;
1081
1082         spin_lock(&scrub->os_lock);
1083         list_for_each_entry(oii, list, oii_list) {
1084                 if (lu_fid_eq(fid, &oii->oii_cache.oic_fid)) {
1085                         spin_unlock(&scrub->os_lock);
1086                         return true;
1087                 }
1088         }
1089         spin_unlock(&scrub->os_lock);
1090
1091         return false;
1092 }
1093
1094 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
1095                           const struct lu_fid *fid,
1096                           const struct lu_object_conf *conf)
1097 {
1098         struct osd_thread_info *info;
1099         struct lu_device *ldev = obj->oo_dt.do_lu.lo_dev;
1100         struct osd_device *dev;
1101         struct osd_idmap_cache *oic;
1102         struct osd_inode_id *id;
1103         struct inode *inode = NULL;
1104         struct lustre_scrub *scrub;
1105         struct scrub_file *sf;
1106         __u32 flags = SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT | SS_AUTO_FULL;
1107         __u32 saved_ino;
1108         __u32 saved_gen;
1109         int result = 0;
1110         int rc1 = 0;
1111         bool remote = false;
1112         bool trusted = true;
1113         bool updated = false;
1114         bool checked = false;
1115         bool stale = false;
1116
1117         ENTRY;
1118
1119         LINVRNT(osd_invariant(obj));
1120         LASSERT(obj->oo_inode == NULL);
1121
1122         if (fid_is_sane(fid) == 0) {
1123                 CERROR("%s: invalid FID "DFID"\n", ldev->ld_obd->obd_name,
1124                        PFID(fid));
1125                 dump_stack();
1126                 RETURN(-EINVAL);
1127         }
1128
1129         dev = osd_dev(ldev);
1130         scrub = &dev->od_scrub.os_scrub;
1131         sf = &scrub->os_file;
1132         info = osd_oti_get(env);
1133         LASSERT(info);
1134         oic = &info->oti_cache;
1135
1136         if (OBD_FAIL_CHECK(OBD_FAIL_SRV_ENOENT))
1137                 RETURN(-ENOENT);
1138
1139         /*
1140          * For the object is created as locking anchor, or for the object to
1141          * be created on disk. No need to osd_oi_lookup() at here because FID
1142          * shouldn't never be re-used, if it's really a duplicate FID from
1143          * unexpected reason, we should be able to detect it later by calling
1144          * do_create->osd_oi_insert().
1145          */
1146         if (conf && conf->loc_flags & LOC_F_NEW)
1147                 RETURN(0);
1148
1149         /* Search order: 1. per-thread cache. */
1150         if (lu_fid_eq(fid, &oic->oic_fid) && likely(oic->oic_dev == dev)) {
1151                 id = &oic->oic_lid;
1152                 goto iget;
1153         }
1154
1155         /* Search order: 2. OI scrub pending list. */
1156         id = &info->oti_id;
1157         memset(id, 0, sizeof(struct osd_inode_id));
1158         if (fid_in_scrub_list(scrub, &scrub->os_inconsistent_items, fid) &&
1159             scrub->os_running)
1160                 RETURN(-EINPROGRESS);
1161
1162         stale = fid_in_scrub_list(scrub, &scrub->os_stale_items, fid);
1163         if (stale && OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_STALE))
1164                 RETURN(-ESTALE);
1165
1166         /*
1167          * The OI mapping in the OI file can be updated by the OI scrub
1168          * when we locate the inode via FID. So it may be not trustable.
1169          */
1170         trusted = false;
1171
1172         /* Search order: 3. OI files. */
1173         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1174         if (result == -ENOENT) {
1175                 if (!fid_is_norm(fid) ||
1176                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
1177                     !ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
1178                                       sf->sf_oi_bitmap))
1179                         GOTO(out, result = 0);
1180
1181                 goto trigger;
1182         }
1183
1184         /* -ESTALE is returned if inode of OST object doesn't exist */
1185         if (result == -ESTALE &&
1186             fid_is_on_ost(info, dev, fid, OI_CHECK_FLD)) {
1187                 GOTO(out, result = 0);
1188         }
1189
1190         if (result)
1191                 GOTO(out, result);
1192
1193 iget:
1194         obj->oo_inode = NULL;
1195         /* for later passes through checks, not true on first pass */
1196         if (!IS_ERR_OR_NULL(inode))
1197                 iput(inode);
1198
1199         inode = osd_iget_check(info, dev, fid, id, trusted);
1200         if (!IS_ERR(inode)) {
1201                 obj->oo_inode = inode;
1202                 result = 0;
1203                 if (remote)
1204                         goto trigger;
1205
1206                 goto check_lma;
1207         }
1208
1209         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_STALE))
1210                 goto trigger;
1211
1212         result = PTR_ERR(inode);
1213         if (result == -ENOENT || result == -ESTALE)
1214                 GOTO(out, result = 0);
1215
1216         if (result != -EREMCHG)
1217                 GOTO(out, result);
1218
1219 trigger:
1220         /* don't trigger repeatedly for stale mapping */
1221         if (stale)
1222                 GOTO(out, result = -ESTALE);
1223
1224         /*
1225          * We still have chance to get the valid inode: for the
1226          * object which is referenced by remote name entry, the
1227          * object on the local MDT will be linked under the dir
1228          * of "/REMOTE_PARENT_DIR" with its FID string as name.
1229          *
1230          * We do not know whether the object for the given FID
1231          * is referenced by some remote name entry or not, and
1232          * especially for DNE II, a multiple-linked object may
1233          * have many name entries reside on many MDTs.
1234          *
1235          * To simplify the operation, OSD will not distinguish
1236          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
1237          * only happened for the RPC from other MDT during the
1238          * OI scrub, or for the client side RPC with FID only,
1239          * such as FID to path, or from old connected client.
1240          */
1241         if (!remote) {
1242                 rc1 = osd_lookup_in_remote_parent(info, dev, fid, id);
1243                 if (!rc1) {
1244                         remote = true;
1245                         trusted = true;
1246                         flags |= SS_AUTO_PARTIAL;
1247                         flags &= ~SS_AUTO_FULL;
1248                         goto iget;
1249                 }
1250         }
1251
1252         if (scrub->os_running) {
1253                 if (scrub->os_partial_scan && !scrub->os_in_join)
1254                         goto join;
1255
1256                 if (IS_ERR_OR_NULL(inode) || result) {
1257                         osd_scrub_oi_insert(dev, fid, id, result == -ENOENT);
1258                         GOTO(out, result = -EINPROGRESS);
1259                 }
1260
1261                 LASSERT(remote);
1262                 LASSERT(obj->oo_inode == inode);
1263
1264                 osd_scrub_oi_insert(dev, fid, id, true);
1265                 goto found;
1266         }
1267
1268         if (dev->od_scrub.os_scrub.os_auto_scrub_interval == AS_NEVER) {
1269                 if (!remote)
1270                         GOTO(out, result = -EREMCHG);
1271
1272                 LASSERT(!result);
1273                 LASSERT(obj->oo_inode == inode);
1274
1275                 osd_add_oi_cache(info, dev, id, fid);
1276                 goto found;
1277         }
1278
1279 join:
1280         if (IS_ERR_OR_NULL(inode) || result)
1281                 osd_scrub_oi_insert(dev, fid, id, result == -ENOENT);
1282
1283         rc1 = osd_scrub_start(env, dev, flags);
1284         CDEBUG_LIMIT(D_LFSCK | D_CONSOLE | D_WARNING,
1285                      "%s: trigger OI scrub by RPC for "DFID"/%u with flags %#x: rc = %d\n",
1286                      osd_name(dev), PFID(fid), id->oii_ino, flags, rc1);
1287         if (rc1 && rc1 != -EALREADY)
1288                 GOTO(out, result = -EREMCHG);
1289
1290         if (IS_ERR_OR_NULL(inode) || result)
1291                 GOTO(out, result = -EINPROGRESS);
1292
1293         LASSERT(remote);
1294         LASSERT(obj->oo_inode == inode);
1295         goto found;
1296
1297 check_lma:
1298         checked = true;
1299         if (unlikely(obj->oo_header))
1300                 goto found;
1301
1302         result = osd_check_lma(env, obj);
1303         if (!result)
1304                 goto found;
1305
1306         LASSERTF(id->oii_ino == inode->i_ino &&
1307                  id->oii_gen == inode->i_generation,
1308                  "locate wrong inode for FID: "DFID", %u/%u => %ld/%u\n",
1309                  PFID(fid), id->oii_ino, id->oii_gen,
1310                  inode->i_ino, inode->i_generation);
1311
1312         saved_ino = inode->i_ino;
1313         saved_gen = inode->i_generation;
1314
1315         if (unlikely(result == -ENODATA)) {
1316                 /*
1317                  * If the OI scrub updated the OI mapping by race, it
1318                  * must be valid. Trust the inode that has no LMA EA.
1319                  */
1320                 if (updated)
1321                         goto found;
1322
1323                 result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1324                 if (!result) {
1325                         /*
1326                          * The OI mapping is still there, the inode is still
1327                          * valid. It is just becaues the inode has no LMA EA.
1328                          */
1329                         if (saved_ino == id->oii_ino &&
1330                             saved_gen == id->oii_gen)
1331                                 goto found;
1332
1333                         /*
1334                          * It is the OI scrub updated the OI mapping by race.
1335                          * The new OI mapping must be valid.
1336                          */
1337                         trusted = true;
1338                         updated = true;
1339                         goto iget;
1340                 }
1341
1342                 /*
1343                  * "result == -ENOENT" means that the OI mappinghas been
1344                  * removed by race, so the inode belongs to other object.
1345                  *
1346                  * Others error can be returned  directly.
1347                  */
1348                 if (result == -ENOENT) {
1349                         LASSERT(trusted);
1350
1351                         obj->oo_inode = NULL;
1352                         result = 0;
1353                 }
1354         }
1355
1356         if (result != -EREMCHG)
1357                 GOTO(out, result);
1358
1359         LASSERT(!updated);
1360
1361         /*
1362          * if two OST objects map to the same inode, and inode mode is
1363          * (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666), which means it's
1364          * reserved by precreate, and not written yet, in this case, don't
1365          * set inode for the object whose FID mismatch, so that it can create
1366          * inode and not block precreate.
1367          */
1368         if (fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) &&
1369             inode->i_mode == (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666)) {
1370                 obj->oo_inode = NULL;
1371                 GOTO(out, result = 0);
1372         }
1373
1374         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1375         /*
1376          * "result == -ENOENT" means the cached OI mapping has been removed
1377          * from the OI file by race, above inode belongs to other object.
1378          */
1379         if (result == -ENOENT) {
1380                 LASSERT(trusted);
1381
1382                 obj->oo_inode = NULL;
1383                 GOTO(out, result = 0);
1384         }
1385
1386         if (result)
1387                 GOTO(out, result);
1388
1389         if (saved_ino == id->oii_ino && saved_gen == id->oii_gen) {
1390                 result = -EREMCHG;
1391                 osd_scrub_refresh_mapping(info, dev, fid, id, DTO_INDEX_DELETE,
1392                                           true, 0, NULL);
1393                 goto trigger;
1394         }
1395
1396         /*
1397          * It is the OI scrub updated the OI mapping by race.
1398          * The new OI mapping must be valid.
1399          */
1400         trusted = true;
1401         updated = true;
1402         goto iget;
1403
1404 found:
1405         if (!checked) {
1406                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
1407                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
1408
1409                 result = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
1410                 if (!result) {
1411                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
1412                             dev->od_is_ost)
1413                                 obj->oo_pfid_in_lma = 1;
1414                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
1415                             !dev->od_is_ost)
1416                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
1417                 } else if (result != -ENODATA) {
1418                         GOTO(out, result);
1419                 }
1420         }
1421
1422         obj->oo_compat_dot_created = 1;
1423         obj->oo_compat_dotdot_created = 1;
1424
1425         if (S_ISDIR(inode->i_mode) &&
1426             (flags & SS_AUTO_PARTIAL || sf->sf_status == SS_SCANNING))
1427                 osd_check_lmv(info, dev, inode);
1428
1429         result = osd_attach_jinode(inode);
1430         if (result)
1431                 GOTO(out, result);
1432
1433         if (!ldiskfs_pdo)
1434                 GOTO(out, result = 0);
1435
1436         LASSERT(!obj->oo_hl_head);
1437         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1438
1439         GOTO(out, result = (!obj->oo_hl_head ? -ENOMEM : 0));
1440
1441 out:
1442         if (!result && stale)
1443                 osd_scrub_oi_resurrect(scrub, fid);
1444
1445         if (result || !obj->oo_inode) {
1446                 if (!IS_ERR_OR_NULL(inode))
1447                         iput(inode);
1448
1449                 obj->oo_inode = NULL;
1450                 if (trusted)
1451                         fid_zero(&oic->oic_fid);
1452         }
1453
1454         LINVRNT(osd_invariant(obj));
1455         return result;
1456 }
1457
1458 /*
1459  * Concurrency: shouldn't matter.
1460  */
1461 static void osd_object_init0(struct osd_object *obj)
1462 {
1463         LASSERT(obj->oo_inode != NULL);
1464         obj->oo_dt.do_body_ops = &osd_body_ops;
1465         obj->oo_dt.do_lu.lo_header->loh_attr |=
1466                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
1467 }
1468
1469 /*
1470  * Concurrency: no concurrent access is possible that early in object
1471  * life-cycle.
1472  */
1473 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
1474                            const struct lu_object_conf *conf)
1475 {
1476         struct osd_object *obj = osd_obj(l);
1477         int result;
1478
1479         LINVRNT(osd_invariant(obj));
1480
1481         if (OBD_FAIL_PRECHECK(OBD_FAIL_MDS_LLOG_UMOUNT_RACE) &&
1482             cfs_fail_val == 2) {
1483                 struct osd_thread_info *info = osd_oti_get(env);
1484                 struct osd_idmap_cache *oic = &info->oti_cache;
1485                 /* invalidate thread cache */
1486                 memset(&oic->oic_fid, 0, sizeof(oic->oic_fid));
1487         }
1488         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
1489                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
1490                 l->lo_header->loh_attr |= LOHA_EXISTS;
1491                 return 0;
1492         }
1493
1494         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
1495         obj->oo_dt.do_body_ops = &osd_body_ops_new;
1496         if (result == 0 && obj->oo_inode != NULL) {
1497                 struct osd_thread_info *oti = osd_oti_get(env);
1498                 struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
1499
1500                 osd_object_init0(obj);
1501                 if (unlikely(obj->oo_header))
1502                         return 0;
1503
1504                 result = osd_get_lma(oti, obj->oo_inode,
1505                                      &oti->oti_obj_dentry, loa);
1506                 if (!result) {
1507                         /*
1508                          * Convert LMAI flags to lustre LMA flags
1509                          * and cache it to oo_lma_flags
1510                          */
1511                         obj->oo_lma_flags =
1512                                 lma_to_lustre_flags(loa->loa_lma.lma_incompat);
1513                 } else if (result == -ENODATA) {
1514                         result = 0;
1515                 }
1516         }
1517         obj->oo_dirent_count = LU_DIRENT_COUNT_UNSET;
1518
1519         LINVRNT(osd_invariant(obj));
1520         return result;
1521 }
1522
1523 /*
1524  * The first part of oxe_buf is xattr name, and is '\0' terminated.
1525  * The left part is for value, binary mode.
1526  */
1527 struct osd_xattr_entry {
1528         struct list_head        oxe_list;
1529         size_t                  oxe_len;
1530         size_t                  oxe_namelen;
1531         bool                    oxe_exist;
1532         struct rcu_head         oxe_rcu;
1533         char                    oxe_buf[0];
1534 };
1535
1536 static int osd_oxc_get(struct osd_object *obj, const char *name,
1537                        struct lu_buf *buf)
1538 {
1539         struct osd_xattr_entry *tmp;
1540         struct osd_xattr_entry *oxe = NULL;
1541         size_t namelen = strlen(name);
1542         int rc;
1543
1544         rcu_read_lock();
1545         list_for_each_entry_rcu(tmp, &obj->oo_xattr_list, oxe_list) {
1546                 if (namelen == tmp->oxe_namelen &&
1547                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1548                         oxe = tmp;
1549                         break;
1550                 }
1551         }
1552
1553         if (oxe == NULL)
1554                 GOTO(out, rc = -ENOENT);
1555
1556         if (!oxe->oxe_exist)
1557                 GOTO(out, rc = -ENODATA);
1558
1559         /* vallen */
1560         rc = oxe->oxe_len - sizeof(*oxe) - oxe->oxe_namelen - 1;
1561         LASSERT(rc > 0);
1562
1563         if (buf->lb_buf == NULL)
1564                 GOTO(out, rc);
1565
1566         if (buf->lb_len < rc)
1567                 GOTO(out, rc = -ERANGE);
1568
1569         memcpy(buf->lb_buf, &oxe->oxe_buf[namelen + 1], rc);
1570 out:
1571         rcu_read_unlock();
1572
1573         return rc;
1574 }
1575
1576 static void osd_oxc_free(struct rcu_head *head)
1577 {
1578         struct osd_xattr_entry *oxe;
1579
1580         oxe = container_of(head, struct osd_xattr_entry, oxe_rcu);
1581         OBD_FREE(oxe, oxe->oxe_len);
1582 }
1583
1584 static void osd_oxc_add(struct osd_object *obj, const char *name,
1585                         const char *buf, int buflen)
1586 {
1587         struct osd_xattr_entry *oxe;
1588         struct osd_xattr_entry *old = NULL;
1589         struct osd_xattr_entry *tmp;
1590         size_t namelen = strlen(name);
1591         size_t len = sizeof(*oxe) + namelen + 1 + buflen;
1592
1593         OBD_ALLOC(oxe, len);
1594         if (oxe == NULL)
1595                 return;
1596
1597         INIT_LIST_HEAD(&oxe->oxe_list);
1598         oxe->oxe_len = len;
1599         oxe->oxe_namelen = namelen;
1600         memcpy(oxe->oxe_buf, name, namelen);
1601         if (buflen > 0) {
1602                 LASSERT(buf != NULL);
1603                 memcpy(oxe->oxe_buf + namelen + 1, buf, buflen);
1604                 oxe->oxe_exist = true;
1605         } else {
1606                 oxe->oxe_exist = false;
1607         }
1608
1609         /* this should be rarely called, just remove old and add new */
1610         spin_lock(&obj->oo_guard);
1611         list_for_each_entry(tmp, &obj->oo_xattr_list, oxe_list) {
1612                 if (namelen == tmp->oxe_namelen &&
1613                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1614                         old = tmp;
1615                         break;
1616                 }
1617         }
1618         if (old != NULL) {
1619                 list_replace_rcu(&old->oxe_list, &oxe->oxe_list);
1620                 call_rcu(&old->oxe_rcu, osd_oxc_free);
1621         } else {
1622                 list_add_tail_rcu(&oxe->oxe_list, &obj->oo_xattr_list);
1623         }
1624         spin_unlock(&obj->oo_guard);
1625 }
1626
1627 static void osd_oxc_del(struct osd_object *obj, const char *name)
1628 {
1629         struct osd_xattr_entry *oxe;
1630         size_t namelen = strlen(name);
1631
1632         spin_lock(&obj->oo_guard);
1633         list_for_each_entry(oxe, &obj->oo_xattr_list, oxe_list) {
1634                 if (namelen == oxe->oxe_namelen &&
1635                     strncmp(name, oxe->oxe_buf, namelen) == 0) {
1636                         list_del_rcu(&oxe->oxe_list);
1637                         call_rcu(&oxe->oxe_rcu, osd_oxc_free);
1638                         break;
1639                 }
1640         }
1641         spin_unlock(&obj->oo_guard);
1642 }
1643
1644 static void osd_oxc_fini(struct osd_object *obj)
1645 {
1646         struct osd_xattr_entry *oxe, *next;
1647
1648         list_for_each_entry_safe(oxe, next, &obj->oo_xattr_list, oxe_list) {
1649                 list_del(&oxe->oxe_list);
1650                 OBD_FREE(oxe, oxe->oxe_len);
1651         }
1652 }
1653
1654 /*
1655  * Concurrency: no concurrent access is possible that late in object
1656  * life-cycle.
1657  */
1658 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
1659 {
1660         struct osd_object *obj = osd_obj(l);
1661         struct lu_object_header *h = obj->oo_header;
1662
1663         LINVRNT(osd_invariant(obj));
1664
1665         osd_oxc_fini(obj);
1666         dt_object_fini(&obj->oo_dt);
1667         if (obj->oo_hl_head != NULL)
1668                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1669         /* obj doesn't contain an lu_object_header, so we don't need call_rcu */
1670         OBD_FREE_PTR(obj);
1671         if (unlikely(h))
1672                 lu_object_header_free(h);
1673 }
1674
1675 /*
1676  * Concurrency: no concurrent access is possible that late in object
1677  * life-cycle.
1678  */
1679 static void osd_index_fini(struct osd_object *o)
1680 {
1681         struct iam_container *bag;
1682
1683         if (o->oo_dir != NULL) {
1684                 bag = &o->oo_dir->od_container;
1685                 if (o->oo_inode != NULL) {
1686                         if (bag->ic_object == o->oo_inode)
1687                                 iam_container_fini(bag);
1688                 }
1689                 OBD_FREE_PTR(o->oo_dir);
1690                 o->oo_dir = NULL;
1691         }
1692 }
1693
1694 enum {
1695         OSD_TXN_OI_DELETE_CREDITS    = 20,
1696         OSD_TXN_INODE_DELETE_CREDITS = 20
1697 };
1698
1699 /*
1700  * Journal
1701  */
1702
1703 #if OSD_THANDLE_STATS
1704 /**
1705  * Set time when the handle is allocated
1706  */
1707 static void osd_th_alloced(struct osd_thandle *oth)
1708 {
1709         oth->oth_alloced = ktime_get();
1710 }
1711
1712 /**
1713  * Set time when the handle started
1714  */
1715 static void osd_th_started(struct osd_thandle *oth)
1716 {
1717         oth->oth_started = ktime_get();
1718 }
1719
1720 /**
1721  * Check whether the we deal with this handle for too long.
1722  */
1723 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
1724                                 ktime_t alloced, ktime_t started,
1725                                 ktime_t closed)
1726 {
1727         ktime_t now = ktime_get();
1728
1729         LASSERT(dev != NULL);
1730
1731         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
1732                             ktime_us_delta(started, alloced));
1733         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
1734                             ktime_us_delta(closed, started));
1735         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
1736                             ktime_us_delta(now, closed));
1737
1738         if (ktime_before(ktime_add_ns(alloced, 30 * NSEC_PER_SEC), now)) {
1739                 CWARN("transaction handle %p was open for too long: now %lld, alloced %lld, started %lld, closed %lld\n",
1740                                 oth, now, alloced, started, closed);
1741                 libcfs_debug_dumpstack(NULL);
1742         }
1743 }
1744
1745 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
1746 {                                                                       \
1747         ktime_t __closed = ktime_get();                                 \
1748         ktime_t __alloced = oth->oth_alloced;                           \
1749         ktime_t __started = oth->oth_started;                           \
1750                                                                         \
1751         expr;                                                           \
1752         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
1753 }
1754
1755 #else /* OSD_THANDLE_STATS */
1756
1757 #define osd_th_alloced(h)                  do {} while(0)
1758 #define osd_th_started(h)                  do {} while(0)
1759 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
1760
1761 #endif /* OSD_THANDLE_STATS */
1762
1763 /*
1764  * Concurrency: doesn't access mutable data.
1765  */
1766 static int osd_param_is_not_sane(const struct osd_device *dev,
1767                                  const struct thandle *th)
1768 {
1769         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
1770
1771         return oh->ot_credits > osd_transaction_size(dev);
1772 }
1773
1774 /*
1775  * Concurrency: shouldn't matter.
1776  */
1777 static void osd_trans_commit_cb(struct super_block *sb,
1778                                 struct ldiskfs_journal_cb_entry *jcb, int error)
1779 {
1780         struct osd_thandle *oh = container_of(jcb, struct osd_thandle, ot_jcb);
1781         struct thandle *th = &oh->ot_super;
1782         struct lu_device *lud = &th->th_dev->dd_lu_dev;
1783         struct osd_device *osd = osd_dev(lud);
1784         struct dt_txn_commit_cb *dcb, *tmp;
1785
1786         LASSERT(oh->ot_handle == NULL);
1787
1788         if (error)
1789                 CERROR("transaction @0x%p commit error: %d\n", th, error);
1790
1791         /* call per-transaction callbacks if any */
1792         list_for_each_entry_safe(dcb, tmp, &oh->ot_commit_dcb_list,
1793                                  dcb_linkage) {
1794                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1795                          "commit callback entry: magic=%x name='%s'\n",
1796                          dcb->dcb_magic, dcb->dcb_name);
1797                 list_del_init(&dcb->dcb_linkage);
1798                 dcb->dcb_func(NULL, th, dcb, error);
1799         }
1800
1801         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
1802         if (atomic_dec_and_test(&osd->od_commit_cb_in_flight))
1803                 wake_up(&osd->od_commit_cb_done);
1804         th->th_dev = NULL;
1805
1806         OBD_FREE_PTR(oh);
1807 }
1808
1809 static struct thandle *osd_trans_create(const struct lu_env *env,
1810                                         struct dt_device *d)
1811 {
1812         struct osd_thread_info *oti = osd_oti_get(env);
1813         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1814         struct osd_thandle *oh;
1815         struct thandle *th;
1816
1817         ENTRY;
1818
1819         if (d->dd_rdonly) {
1820                 CERROR("%s: someone try to start transaction under "
1821                        "readonly mode, should be disabled.\n",
1822                        osd_name(osd_dt_dev(d)));
1823                 dump_stack();
1824                 RETURN(ERR_PTR(-EROFS));
1825         }
1826
1827         /* on pending IO in this thread should left from prev. request */
1828         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
1829
1830         sb_start_write(osd_sb(osd_dt_dev(d)));
1831
1832         OBD_ALLOC_GFP(oh, sizeof(*oh), GFP_NOFS);
1833         if (!oh) {
1834                 sb_end_write(osd_sb(osd_dt_dev(d)));
1835                 RETURN(ERR_PTR(-ENOMEM));
1836         }
1837
1838         oh->ot_quota_trans = &oti->oti_quota_trans;
1839         memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
1840         th = &oh->ot_super;
1841         th->th_dev = d;
1842         th->th_result = 0;
1843         oh->ot_credits = 0;
1844         oh->oh_declared_ext = 0;
1845         INIT_LIST_HEAD(&oh->ot_commit_dcb_list);
1846         INIT_LIST_HEAD(&oh->ot_stop_dcb_list);
1847         INIT_LIST_HEAD(&oh->ot_trunc_locks);
1848         osd_th_alloced(oh);
1849
1850         memset(oti->oti_declare_ops, 0,
1851                sizeof(oti->oti_declare_ops));
1852         memset(oti->oti_declare_ops_cred, 0,
1853                sizeof(oti->oti_declare_ops_cred));
1854         memset(oti->oti_declare_ops_used, 0,
1855                sizeof(oti->oti_declare_ops_used));
1856
1857         oti->oti_ins_cache_depth++;
1858
1859         RETURN(th);
1860 }
1861
1862 void osd_trans_dump_creds(const struct lu_env *env, struct thandle *th)
1863 {
1864         struct osd_thread_info *oti = osd_oti_get(env);
1865         struct osd_thandle *oh;
1866
1867         oh = container_of(th, struct osd_thandle, ot_super);
1868         LASSERT(oh != NULL);
1869
1870         CWARN("  create: %u/%u/%u, destroy: %u/%u/%u\n",
1871               oti->oti_declare_ops[OSD_OT_CREATE],
1872               oti->oti_declare_ops_cred[OSD_OT_CREATE],
1873               oti->oti_declare_ops_used[OSD_OT_CREATE],
1874               oti->oti_declare_ops[OSD_OT_DESTROY],
1875               oti->oti_declare_ops_cred[OSD_OT_DESTROY],
1876               oti->oti_declare_ops_used[OSD_OT_DESTROY]);
1877         CWARN("  attr_set: %u/%u/%u, xattr_set: %u/%u/%u\n",
1878               oti->oti_declare_ops[OSD_OT_ATTR_SET],
1879               oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1880               oti->oti_declare_ops_used[OSD_OT_ATTR_SET],
1881               oti->oti_declare_ops[OSD_OT_XATTR_SET],
1882               oti->oti_declare_ops_cred[OSD_OT_XATTR_SET],
1883               oti->oti_declare_ops_used[OSD_OT_XATTR_SET]);
1884         CWARN("  write: %u/%u/%u, punch: %u/%u/%u, quota %u/%u/%u\n",
1885               oti->oti_declare_ops[OSD_OT_WRITE],
1886               oti->oti_declare_ops_cred[OSD_OT_WRITE],
1887               oti->oti_declare_ops_used[OSD_OT_WRITE],
1888               oti->oti_declare_ops[OSD_OT_PUNCH],
1889               oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1890               oti->oti_declare_ops_used[OSD_OT_PUNCH],
1891               oti->oti_declare_ops[OSD_OT_QUOTA],
1892               oti->oti_declare_ops_cred[OSD_OT_QUOTA],
1893               oti->oti_declare_ops_used[OSD_OT_QUOTA]);
1894         CWARN("  insert: %u/%u/%u, delete: %u/%u/%u\n",
1895               oti->oti_declare_ops[OSD_OT_INSERT],
1896               oti->oti_declare_ops_cred[OSD_OT_INSERT],
1897               oti->oti_declare_ops_used[OSD_OT_INSERT],
1898               oti->oti_declare_ops[OSD_OT_DELETE],
1899               oti->oti_declare_ops_cred[OSD_OT_DELETE],
1900               oti->oti_declare_ops_used[OSD_OT_DELETE]);
1901         CWARN("  ref_add: %u/%u/%u, ref_del: %u/%u/%u\n",
1902               oti->oti_declare_ops[OSD_OT_REF_ADD],
1903               oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1904               oti->oti_declare_ops_used[OSD_OT_REF_ADD],
1905               oti->oti_declare_ops[OSD_OT_REF_DEL],
1906               oti->oti_declare_ops_cred[OSD_OT_REF_DEL],
1907               oti->oti_declare_ops_used[OSD_OT_REF_DEL]);
1908 }
1909
1910 /*
1911  * Concurrency: shouldn't matter.
1912  */
1913 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
1914                            struct thandle *th)
1915 {
1916         struct osd_thread_info *oti = osd_oti_get(env);
1917         struct osd_device *dev = osd_dt_dev(d);
1918         handle_t *jh;
1919         struct osd_thandle *oh;
1920         int rc;
1921
1922         ENTRY;
1923
1924         LASSERT(current->journal_info == NULL);
1925
1926         oh = container_of(th, struct osd_thandle, ot_super);
1927         LASSERT(oh != NULL);
1928         LASSERT(oh->ot_handle == NULL);
1929
1930         rc = dt_txn_hook_start(env, d, th);
1931         if (rc != 0)
1932                 GOTO(out, rc);
1933
1934         if (unlikely(osd_param_is_not_sane(dev, th))) {
1935                 static unsigned long last_printed;
1936                 static int last_credits;
1937
1938                 /*
1939                  * don't make noise on a tiny testing systems
1940                  * actual credits misuse will be caught anyway
1941                  */
1942                 if (last_credits != oh->ot_credits &&
1943                     time_after(jiffies, last_printed +
1944                                cfs_time_seconds(60)) &&
1945                     osd_transaction_size(dev) > 512) {
1946                         CWARN("%s: credits %u > trans_max %u\n", osd_name(dev),
1947                               oh->ot_credits, osd_transaction_size(dev));
1948                         osd_trans_dump_creds(env, th);
1949                         libcfs_debug_dumpstack(NULL);
1950                         last_credits = oh->ot_credits;
1951                         last_printed = jiffies;
1952                 }
1953                 /*
1954                  * XXX Limit the credits to 'max_transaction_buffers', and
1955                  *     let the underlying filesystem to catch the error if
1956                  *     we really need so many credits.
1957                  *
1958                  *     This should be removed when we can calculate the
1959                  *     credits precisely.
1960                  */
1961                 oh->ot_credits = osd_transaction_size(dev);
1962         } else if (ldiskfs_track_declares_assert != 0) {
1963                 /*
1964                  * reserve few credits to prevent an assertion in JBD
1965                  * our debugging mechanism will be able to detected
1966                  * overuse. this can help to debug single-update
1967                  * transactions
1968                  */
1969                 oh->ot_credits += 10;
1970                 if (unlikely(osd_param_is_not_sane(dev, th)))
1971                         oh->ot_credits = osd_transaction_size(dev);
1972         }
1973
1974         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_TXN_START))
1975                 GOTO(out, rc = -EIO);
1976
1977          /*
1978           * we ignore quota checks for system-owned files, but still
1979           * need to count blocks for uid/gid/projid
1980           */
1981         osd_trans_declare_op(env, oh, OSD_OT_QUOTA, 3);
1982
1983         /*
1984          * XXX temporary stuff. Some abstraction layer should
1985          * be used.
1986          */
1987         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
1988         osd_th_started(oh);
1989         if (!IS_ERR(jh)) {
1990                 oh->ot_handle = jh;
1991                 LASSERT(oti->oti_txns == 0);
1992
1993                 atomic_inc(&dev->od_commit_cb_in_flight);
1994                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
1995                               "osd-tx", th);
1996                 oti->oti_txns++;
1997                 rc = 0;
1998         } else {
1999                 rc = PTR_ERR(jh);
2000         }
2001 out:
2002         RETURN(rc);
2003 }
2004
2005 static int osd_seq_exists(const struct lu_env *env,
2006                           struct osd_device *osd, u64 seq)
2007 {
2008         struct lu_seq_range *range = &osd_oti_get(env)->oti_seq_range;
2009         struct seq_server_site *ss = osd_seq_site(osd);
2010         int rc;
2011
2012         ENTRY;
2013
2014         LASSERT(ss != NULL);
2015         LASSERT(ss->ss_server_fld != NULL);
2016
2017         rc = osd_fld_lookup(env, osd, seq, range);
2018         if (rc != 0) {
2019                 if (rc != -ENOENT)
2020                         CERROR("%s: can't lookup FLD sequence %#llx: rc = %d\n",
2021                                osd_name(osd), seq, rc);
2022                 RETURN(0);
2023         }
2024
2025         RETURN(ss->ss_node_id == range->lsr_index);
2026 }
2027
2028 static void osd_trans_stop_cb(struct osd_thandle *oth, int result)
2029 {
2030         struct dt_txn_commit_cb *dcb;
2031         struct dt_txn_commit_cb *tmp;
2032
2033         /* call per-transaction stop callbacks if any */
2034         list_for_each_entry_safe(dcb, tmp, &oth->ot_stop_dcb_list,
2035                                  dcb_linkage) {
2036                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
2037                          "commit callback entry: magic=%x name='%s'\n",
2038                          dcb->dcb_magic, dcb->dcb_name);
2039                 list_del_init(&dcb->dcb_linkage);
2040                 dcb->dcb_func(NULL, &oth->ot_super, dcb, result);
2041         }
2042 }
2043
2044 /*
2045  * Concurrency: shouldn't matter.
2046  */
2047 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
2048                           struct thandle *th)
2049 {
2050         struct osd_thread_info *oti = osd_oti_get(env);
2051         struct osd_thandle *oh;
2052         struct osd_iobuf *iobuf = &oti->oti_iobuf;
2053         struct osd_device *osd = osd_dt_dev(th->th_dev);
2054         struct qsd_instance *qsd = osd_def_qsd(osd);
2055         struct lquota_trans *qtrans;
2056         LIST_HEAD(truncates);
2057         int rc = 0, remove_agents = 0;
2058
2059         ENTRY;
2060
2061         oh = container_of(th, struct osd_thandle, ot_super);
2062
2063         remove_agents = oh->ot_remove_agents;
2064
2065         qtrans = oh->ot_quota_trans;
2066         oh->ot_quota_trans = NULL;
2067
2068         /* move locks to local list, stop tx, execute truncates */
2069         list_splice(&oh->ot_trunc_locks, &truncates);
2070
2071         if (oh->ot_handle != NULL) {
2072                 int rc2;
2073
2074                 handle_t *hdl = oh->ot_handle;
2075
2076                 /*
2077                  * add commit callback
2078                  * notice we don't do this in osd_trans_start()
2079                  * as underlying transaction can change during truncate
2080                  */
2081                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
2082                                              &oh->ot_jcb);
2083
2084                 LASSERT(oti->oti_txns == 1);
2085                 oti->oti_txns--;
2086
2087                 rc = dt_txn_hook_stop(env, th);
2088                 if (rc != 0)
2089                         CERROR("%s: failed in transaction hook: rc = %d\n",
2090                                osd_name(osd), rc);
2091
2092                 osd_trans_stop_cb(oh, rc);
2093                 /* hook functions might modify th_sync */
2094                 hdl->h_sync = th->th_sync;
2095
2096                 oh->ot_handle = NULL;
2097                 OSD_CHECK_SLOW_TH(oh, osd, rc2 = ldiskfs_journal_stop(hdl));
2098                 if (rc2 != 0)
2099                         CERROR("%s: failed to stop transaction: rc = %d\n",
2100                                osd_name(osd), rc2);
2101                 if (!rc)
2102                         rc = rc2;
2103
2104                 /* We preserve the origin behavior of ignoring any
2105                  * failures with the underlying punch / truncate
2106                  * operation. We do record for debugging if an error
2107                  * does occur in the lctl dk logs.
2108                  */
2109                 rc2 = osd_process_truncates(env, &truncates);
2110                 if (rc2 != 0)
2111                         CERROR("%s: failed truncate process: rc = %d\n",
2112                                osd_name(osd), rc2);
2113         } else {
2114                 osd_trans_stop_cb(oh, th->th_result);
2115                 OBD_FREE_PTR(oh);
2116         }
2117
2118         osd_trunc_unlock_all(env, &truncates);
2119
2120         /* inform the quota slave device that the transaction is stopping */
2121         qsd_op_end(env, qsd, qtrans);
2122
2123         /*
2124          * as we want IO to journal and data IO be concurrent, we don't block
2125          * awaiting data IO completion in osd_do_bio(), instead we wait here
2126          * once transaction is submitted to the journal. all reqular requests
2127          * don't do direct IO (except read/write), thus this wait_event becomes
2128          * no-op for them.
2129          *
2130          * IMPORTANT: we have to wait till any IO submited by the thread is
2131          * completed otherwise iobuf may be corrupted by different request
2132          */
2133         wait_event(iobuf->dr_wait,
2134                        atomic_read(&iobuf->dr_numreqs) == 0);
2135         osd_fini_iobuf(osd, iobuf);
2136         if (!rc)
2137                 rc = iobuf->dr_error;
2138
2139         if (unlikely(remove_agents != 0))
2140                 osd_process_scheduled_agent_removals(env, osd);
2141
2142         LASSERT(oti->oti_ins_cache_depth > 0);
2143         oti->oti_ins_cache_depth--;
2144         /* reset OI cache for safety */
2145         if (oti->oti_ins_cache_depth == 0)
2146                 oti->oti_ins_cache_used = 0;
2147
2148         sb_end_write(osd_sb(osd));
2149
2150         RETURN(rc);
2151 }
2152
2153 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
2154 {
2155         struct osd_thandle *oh = container_of(th, struct osd_thandle,
2156                                               ot_super);
2157
2158         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
2159         LASSERT(&dcb->dcb_func != NULL);
2160         if (dcb->dcb_flags & DCB_TRANS_STOP)
2161                 list_add(&dcb->dcb_linkage, &oh->ot_stop_dcb_list);
2162         else
2163                 list_add(&dcb->dcb_linkage, &oh->ot_commit_dcb_list);
2164
2165         return 0;
2166 }
2167
2168 /*
2169  * Called just before object is freed. Releases all resources except for
2170  * object itself (that is released by osd_object_free()).
2171  *
2172  * Concurrency: no concurrent access is possible that late in object
2173  * life-cycle.
2174  */
2175 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
2176 {
2177         struct osd_object *obj = osd_obj(l);
2178         struct qsd_instance *qsd = osd_def_qsd(osd_obj2dev(obj));
2179         struct inode *inode = obj->oo_inode;
2180         __u64 projid;
2181         qid_t uid;
2182         qid_t gid;
2183
2184         LINVRNT(osd_invariant(obj));
2185
2186         /*
2187          * If object is unlinked remove fid->ino mapping from object index.
2188          */
2189
2190         osd_index_fini(obj);
2191
2192         if (!inode)
2193                 return;
2194
2195         if (osd_has_index(obj) &&  obj->oo_dt.do_index_ops == &osd_index_iam_ops)
2196                 ldiskfs_set_inode_flag(inode, LDISKFS_INODE_JOURNAL_DATA);
2197
2198         uid = i_uid_read(inode);
2199         gid = i_gid_read(inode);
2200         projid = i_projid_read(inode);
2201
2202         obj->oo_inode = NULL;
2203         iput(inode);
2204
2205         /* do not rebalance quota if the caller needs to release memory
2206          * otherwise qsd_refresh_usage() may went into a new ldiskfs
2207          * transaction and risk to deadlock - LU-12178 */
2208         if (current->flags & (PF_MEMALLOC | PF_KSWAPD))
2209                 return;
2210
2211         if (!obj->oo_header && qsd) {
2212                 struct osd_thread_info *info = osd_oti_get(env);
2213                 struct lquota_id_info *qi = &info->oti_qi;
2214
2215                 /* Release granted quota to master if necessary */
2216                 qi->lqi_id.qid_uid = uid;
2217                 qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
2218
2219                 qi->lqi_id.qid_uid = gid;
2220                 qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
2221
2222                 qi->lqi_id.qid_uid = projid;
2223                 qsd_op_adjust(env, qsd, &qi->lqi_id, PRJQUOTA);
2224         }
2225 }
2226
2227 /*
2228  * Concurrency: ->loo_object_release() is called under site spin-lock.
2229  */
2230 static void osd_object_release(const struct lu_env *env,
2231                                struct lu_object *l)
2232 {
2233         struct osd_object *o = osd_obj(l);
2234
2235         /*
2236          * nobody should be releasing a non-destroyed object with nlink=0
2237          * the API allows this, but ldiskfs doesn't like and then report
2238          * this inode as deleted
2239          */
2240         LASSERT(!(o->oo_destroyed == 0 && o->oo_inode &&
2241                   o->oo_inode->i_nlink == 0));
2242 }
2243
2244 /*
2245  * Concurrency: shouldn't matter.
2246  */
2247 static int osd_object_print(const struct lu_env *env, void *cookie,
2248                             lu_printer_t p, const struct lu_object *l)
2249 {
2250         struct osd_object *o = osd_obj(l);
2251         struct iam_descr *d;
2252
2253         if (o->oo_dir != NULL)
2254                 d = o->oo_dir->od_container.ic_descr;
2255         else
2256                 d = NULL;
2257         return (*p)(env, cookie,
2258                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
2259                     o, o->oo_inode,
2260                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
2261                     o->oo_inode ? o->oo_inode->i_generation : 0,
2262                     d ? d->id_ops->id_name : "plain");
2263 }
2264
2265 /*
2266  * Concurrency: shouldn't matter.
2267  */
2268 int osd_statfs(const struct lu_env *env, struct dt_device *d,
2269                 struct obd_statfs *sfs, struct obd_statfs_info *info)
2270 {
2271         struct osd_device *osd = osd_dt_dev(d);
2272         struct super_block *sb = osd_sb(osd);
2273         struct kstatfs *ksfs;
2274         __u64 reserved;
2275         int result = 0;
2276
2277         if (unlikely(osd->od_mnt == NULL))
2278                 return -EINPROGRESS;
2279
2280         /* osd_lproc.c call this without env, allocate ksfs for that case */
2281         if (unlikely(env == NULL)) {
2282                 OBD_ALLOC_PTR(ksfs);
2283                 if (ksfs == NULL)
2284                         return -ENOMEM;
2285         } else {
2286                 ksfs = &osd_oti_get(env)->oti_ksfs;
2287         }
2288
2289         result = sb->s_op->statfs(sb->s_root, ksfs);
2290         if (result)
2291                 goto out;
2292
2293         statfs_pack(sfs, ksfs);
2294         if (unlikely(sb->s_flags & SB_RDONLY))
2295                 sfs->os_state |= OS_STATFS_READONLY;
2296
2297         sfs->os_state |= osd->od_nonrotational ? OS_STATFS_NONROT : 0;
2298
2299         if (ldiskfs_has_feature_extents(sb))
2300                 sfs->os_maxbytes = sb->s_maxbytes;
2301         else
2302                 sfs->os_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2303
2304         /*
2305          * Reserve some space so to avoid fragmenting the filesystem too much.
2306          * Fragmentation not only impacts performance, but can also increase
2307          * metadata overhead significantly, causing grant calculation to be
2308          * wrong.
2309          *
2310          * Reserve 0.78% of total space, at least 8MB for small filesystems.
2311          */
2312         BUILD_BUG_ON(OSD_STATFS_RESERVED <= LDISKFS_MAX_BLOCK_SIZE);
2313         reserved = OSD_STATFS_RESERVED >> sb->s_blocksize_bits;
2314         if (likely(sfs->os_blocks >= reserved << OSD_STATFS_RESERVED_SHIFT))
2315                 reserved = sfs->os_blocks >> OSD_STATFS_RESERVED_SHIFT;
2316
2317         sfs->os_blocks -= reserved;
2318         sfs->os_bfree  -= min(reserved, sfs->os_bfree);
2319         sfs->os_bavail -= min(reserved, sfs->os_bavail);
2320
2321 out:
2322         if (unlikely(env == NULL))
2323                 OBD_FREE_PTR(ksfs);
2324         return result;
2325 }
2326
2327 /**
2328  * Estimate space needed for file creations. We assume the largest filename
2329  * which is 2^64 - 1, hence a filename of 20 chars.
2330  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
2331  */
2332 #ifdef __LDISKFS_DIR_REC_LEN
2333 # define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
2334 #elif defined  LDISKFS_DIR_REC_LEN_WITH_DIR
2335 # define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20, NULL)
2336 #else
2337 # define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
2338 #endif
2339
2340 /*
2341  * Concurrency: doesn't access mutable data.
2342  */
2343 static void osd_conf_get(const struct lu_env *env,
2344                          const struct dt_device *dev,
2345                          struct dt_device_param *param)
2346 {
2347         struct osd_device *d = osd_dt_dev(dev);
2348         struct super_block *sb = osd_sb(d);
2349         struct blk_integrity *bi = bdev_get_integrity(sb->s_bdev);
2350         const char *name;
2351         int ea_overhead;
2352
2353         /*
2354          * XXX should be taken from not-yet-existing fs abstraction layer.
2355          */
2356         param->ddp_max_name_len = LDISKFS_NAME_LEN;
2357         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
2358         param->ddp_symlink_max  = sb->s_blocksize;
2359         param->ddp_mount_type   = LDD_MT_LDISKFS;
2360         if (ldiskfs_has_feature_extents(sb))
2361                 param->ddp_maxbytes = sb->s_maxbytes;
2362         else
2363                 param->ddp_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2364         /*
2365          * inode are statically allocated, so per-inode space consumption
2366          * is the space consumed by the directory entry
2367          */
2368         param->ddp_inodespace     = PER_OBJ_USAGE;
2369         /*
2370          * EXT_INIT_MAX_LEN is the theoretical maximum extent size (32k blocks
2371          * is 128MB) which is unlikely to be hit in real life. Report a smaller
2372          * maximum length to not under-count the actual number of extents
2373          * needed for writing a file if there are sub-optimal block allocations.
2374          */
2375         param->ddp_max_extent_blks = EXT_INIT_MAX_LEN >> 1;
2376         /* worst-case extent insertion metadata overhead */
2377         param->ddp_extent_tax = 6 * LDISKFS_BLOCK_SIZE(sb);
2378         param->ddp_mntopts = 0;
2379         if (test_opt(sb, XATTR_USER))
2380                 param->ddp_mntopts |= MNTOPT_USERXATTR;
2381         if (test_opt(sb, POSIX_ACL))
2382                 param->ddp_mntopts |= MNTOPT_ACL;
2383
2384         /*
2385          * LOD might calculate the max stripe count based on max_ea_size,
2386          * so we need take account in the overhead as well,
2387          * xattr_header + magic + xattr_entry_head
2388          */
2389         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
2390                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
2391
2392 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
2393         if (ldiskfs_has_feature_ea_inode(sb))
2394                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
2395                                                                 ea_overhead;
2396         else
2397 #endif
2398                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
2399
2400         if (param->ddp_max_ea_size > OBD_MAX_EA_SIZE)
2401                 param->ddp_max_ea_size = OBD_MAX_EA_SIZE;
2402
2403         /*
2404          * Preferred RPC size for efficient disk IO.  4MB shows good
2405          * all-around performance for ldiskfs, but use bigalloc chunk size
2406          * by default if larger.
2407          */
2408 #if defined(LDISKFS_CLUSTER_SIZE)
2409         if (LDISKFS_CLUSTER_SIZE(sb) > DT_DEF_BRW_SIZE)
2410                 param->ddp_brw_size = LDISKFS_CLUSTER_SIZE(sb);
2411         else
2412 #endif
2413                 param->ddp_brw_size = DT_DEF_BRW_SIZE;
2414
2415         param->ddp_t10_cksum_type = 0;
2416         if (bi) {
2417                 unsigned short interval = blk_integrity_interval(bi);
2418                 name = blk_integrity_name(bi);
2419                 /*
2420                  * Expected values:
2421                  * T10-DIF-TYPE1-CRC
2422                  * T10-DIF-TYPE2-CRC
2423                  * T10-DIF-TYPE3-CRC
2424                  * T10-DIF-TYPE1-IP
2425                  * T10-DIF-TYPE2-IP
2426                  * T10-DIF-TYPE3-IP
2427                  */
2428                 if (strncmp(name, "T10-DIF-TYPE",
2429                             sizeof("T10-DIF-TYPE") - 1) == 0) {
2430                         /* also skip "1/2/3-" at end */
2431                         const int type_off = sizeof("T10-DIF-TYPE.");
2432                         char type_number = name[type_off - 2];
2433
2434                         if (interval != 512 && interval != 4096) {
2435                                 CERROR("%s: unsupported T10PI sector size %u\n",
2436                                        d->od_svname, interval);
2437                                 goto out;
2438                         }
2439                         switch (type_number) {
2440                         case '1':
2441                                 d->od_t10_type = OSD_T10_TYPE1;
2442                                 break;
2443                         case '2':
2444                                 d->od_t10_type = OSD_T10_TYPE2;
2445                                 break;
2446                         case '3':
2447                                 d->od_t10_type = OSD_T10_TYPE3;
2448                                 break;
2449                         default:
2450                                 CERROR("%s: unsupported T10PI type %s\n",
2451                                        d->od_svname, name);
2452                                 goto out;
2453                         }
2454                         if (strcmp(name + type_off, "CRC") == 0) {
2455                                 d->od_t10_type |= OSD_T10_TYPE_CRC;
2456                                 param->ddp_t10_cksum_type = interval == 512 ?
2457                                         OBD_CKSUM_T10CRC512 :
2458                                         OBD_CKSUM_T10CRC4K;
2459                         } else if (strcmp(name + type_off, "IP") == 0) {
2460                                 d->od_t10_type |= OSD_T10_TYPE_IP;
2461                                 param->ddp_t10_cksum_type = interval == 512 ?
2462                                         OBD_CKSUM_T10IP512 :
2463                                         OBD_CKSUM_T10IP4K;
2464                         } else {
2465                                 CERROR("%s: unsupported checksum type of T10PI type '%s'\n",
2466                                        d->od_svname, name);
2467                                 d->od_t10_type = 0;
2468                         }
2469
2470                 } else {
2471                         CERROR("%s: unsupported T10PI type '%s'\n",
2472                                d->od_svname, name);
2473                 }
2474         }
2475
2476 out:
2477         param->ddp_has_lseek_data_hole = true;
2478 }
2479
2480 static struct super_block *osd_mnt_sb_get(const struct dt_device *d)
2481 {
2482         return osd_sb(osd_dt_dev(d));
2483 }
2484
2485 /*
2486  * Concurrency: shouldn't matter.
2487  */
2488 static int osd_sync(const struct lu_env *env, struct dt_device *d)
2489 {
2490         int rc;
2491         struct super_block *s = osd_sb(osd_dt_dev(d));
2492         ENTRY;
2493
2494         down_read(&s->s_umount);
2495         rc = s->s_op->sync_fs(s, 1);
2496         up_read(&s->s_umount);
2497
2498         CDEBUG(D_CACHE, "%s: synced OSD: rc = %d\n", osd_dt_dev(d)->od_svname,
2499                rc);
2500
2501         return rc;
2502 }
2503
2504 /**
2505  * Start commit for OSD device.
2506  *
2507  * An implementation of dt_commit_async method for OSD device.
2508  * Asychronously starts underlayng fs sync and thereby a transaction
2509  * commit.
2510  *
2511  * \param env environment
2512  * \param d dt device
2513  *
2514  * \see dt_device_operations
2515  */
2516 static int osd_commit_async(const struct lu_env *env,
2517                             struct dt_device *d)
2518 {
2519         struct super_block *s = osd_sb(osd_dt_dev(d));
2520         int rc;
2521
2522         ENTRY;
2523
2524         CDEBUG(D_HA, "%s: async commit OSD\n", osd_dt_dev(d)->od_svname);
2525         down_read(&s->s_umount);
2526         rc = s->s_op->sync_fs(s, 0);
2527         up_read(&s->s_umount);
2528
2529         RETURN(rc);
2530 }
2531
2532 /*
2533  * Concurrency: shouldn't matter.
2534  */
2535 static int osd_ro(const struct lu_env *env, struct dt_device *d)
2536 {
2537         struct super_block *sb = osd_sb(osd_dt_dev(d));
2538         struct block_device *dev = sb->s_bdev;
2539         int rc = -EOPNOTSUPP;
2540
2541         ENTRY;
2542
2543         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
2544                osd_dt_dev(d)->od_svname, (long)dev, rc);
2545
2546         RETURN(rc);
2547 }
2548
2549 /**
2550  * Note: we do not count into QUOTA here.
2551  * If we mount with --data_journal we may need more.
2552  */
2553 const int osd_dto_credits_noquota[DTO_NR] = {
2554         /**
2555          * Insert.
2556          * INDEX_EXTRA_TRANS_BLOCKS(8) +
2557          * SINGLEDATA_TRANS_BLOCKS(8)
2558          * XXX Note: maybe iam need more, since iam have more level than
2559          *           EXT3 htree.
2560          */
2561         [DTO_INDEX_INSERT]  = 16,
2562         /**
2563          * Delete
2564          * just modify a single entry, probably merge few within a block
2565          */
2566         [DTO_INDEX_DELETE]  = 1,
2567         /**
2568          * Used for OI scrub
2569          */
2570         [DTO_INDEX_UPDATE]  = 16,
2571         /**
2572          * 4(inode, inode bits, groups, GDT)
2573          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
2574          */
2575         [DTO_OBJECT_CREATE] = 4,
2576         /**
2577          * 4(inode, inode bits, groups, GDT)
2578          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
2579          */
2580         [DTO_OBJECT_DELETE] = 4,
2581         /**
2582          * Attr set credits (inode)
2583          */
2584         [DTO_ATTR_SET_BASE] = 1,
2585         /**
2586          * Xattr set. The same as xattr of EXT3.
2587          * DATA_TRANS_BLOCKS(14)
2588          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
2589          * are also counted in. Do not know why?
2590          */
2591         [DTO_XATTR_SET]     = 14,
2592         /**
2593          * credits for inode change during write.
2594          */
2595         [DTO_WRITE_BASE]    = 3,
2596         /**
2597          * credits for single block write.
2598          */
2599         [DTO_WRITE_BLOCK]   = 14,
2600         /**
2601          * Attr set credits for chown.
2602          * This is extra credits for setattr, and it is null without quota
2603          */
2604         [DTO_ATTR_SET_CHOWN] = 0
2605 };
2606
2607 /* reserve or free quota for some operation */
2608 static int osd_reserve_or_free_quota(const struct lu_env *env,
2609                                      struct dt_device *dev,
2610                                      struct lquota_id_info *qi)
2611 {
2612         struct osd_device       *osd = osd_dt_dev(dev);
2613         struct qsd_instance     *qsd = NULL;
2614         int rc;
2615
2616         ENTRY;
2617
2618         if (qi->lqi_is_blk)
2619                 qsd = osd->od_quota_slave_dt;
2620         else
2621                 qsd = osd->od_quota_slave_md;
2622
2623         rc = qsd_reserve_or_free_quota(env, qsd, qi);
2624         RETURN(rc);
2625 }
2626
2627 static const struct dt_device_operations osd_dt_ops = {
2628         .dt_root_get              = osd_root_get,
2629         .dt_statfs                = osd_statfs,
2630         .dt_trans_create          = osd_trans_create,
2631         .dt_trans_start           = osd_trans_start,
2632         .dt_trans_stop            = osd_trans_stop,
2633         .dt_trans_cb_add          = osd_trans_cb_add,
2634         .dt_conf_get              = osd_conf_get,
2635         .dt_mnt_sb_get            = osd_mnt_sb_get,
2636         .dt_sync                  = osd_sync,
2637         .dt_ro                    = osd_ro,
2638         .dt_commit_async          = osd_commit_async,
2639         .dt_reserve_or_free_quota = osd_reserve_or_free_quota,
2640 };
2641
2642 static void osd_read_lock(const struct lu_env *env, struct dt_object *dt,
2643                           unsigned int role)
2644 {
2645         struct osd_object *obj = osd_dt_obj(dt);
2646         struct osd_thread_info *oti = osd_oti_get(env);
2647
2648         LINVRNT(osd_invariant(obj));
2649
2650         LASSERT(obj->oo_owner != env);
2651         down_read_nested(&obj->oo_sem, role);
2652
2653         LASSERT(obj->oo_owner == NULL);
2654         oti->oti_r_locks++;
2655 }
2656
2657 static void osd_write_lock(const struct lu_env *env, struct dt_object *dt,
2658                            unsigned int role)
2659 {
2660         struct osd_object *obj = osd_dt_obj(dt);
2661         struct osd_thread_info *oti = osd_oti_get(env);
2662
2663         LINVRNT(osd_invariant(obj));
2664
2665         LASSERT(obj->oo_owner != env);
2666         down_write_nested(&obj->oo_sem, role);
2667
2668         LASSERT(obj->oo_owner == NULL);
2669         obj->oo_owner = env;
2670         oti->oti_w_locks++;
2671 }
2672
2673 static void osd_read_unlock(const struct lu_env *env, struct dt_object *dt)
2674 {
2675         struct osd_object *obj = osd_dt_obj(dt);
2676         struct osd_thread_info *oti = osd_oti_get(env);
2677
2678         LINVRNT(osd_invariant(obj));
2679
2680         LASSERT(oti->oti_r_locks > 0);
2681         oti->oti_r_locks--;
2682         up_read(&obj->oo_sem);
2683 }
2684
2685 static void osd_write_unlock(const struct lu_env *env, struct dt_object *dt)
2686 {
2687         struct osd_object *obj = osd_dt_obj(dt);
2688         struct osd_thread_info *oti = osd_oti_get(env);
2689
2690         LINVRNT(osd_invariant(obj));
2691
2692         LASSERT(obj->oo_owner == env);
2693         LASSERT(oti->oti_w_locks > 0);
2694         oti->oti_w_locks--;
2695         obj->oo_owner = NULL;
2696         up_write(&obj->oo_sem);
2697 }
2698
2699 static int osd_write_locked(const struct lu_env *env, struct dt_object *dt)
2700 {
2701         struct osd_object *obj = osd_dt_obj(dt);
2702
2703         LINVRNT(osd_invariant(obj));
2704
2705         return obj->oo_owner == env;
2706 }
2707
2708 static void osd_inode_getattr(const struct lu_env *env,
2709                               struct inode *inode, struct lu_attr *attr)
2710 {
2711         attr->la_valid  |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
2712                            LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
2713                            LA_PROJID | LA_FLAGS | LA_NLINK | LA_RDEV |
2714                            LA_BLKSIZE | LA_TYPE | LA_BTIME;
2715
2716         attr->la_atime = inode->i_atime.tv_sec;
2717         attr->la_mtime = inode->i_mtime.tv_sec;
2718         attr->la_ctime = inode->i_ctime.tv_sec;
2719         attr->la_btime = LDISKFS_I(inode)->i_crtime.tv_sec;
2720         attr->la_mode    = inode->i_mode;
2721         attr->la_size    = i_size_read(inode);
2722         attr->la_blocks  = inode->i_blocks;
2723         attr->la_uid     = i_uid_read(inode);
2724         attr->la_gid     = i_gid_read(inode);
2725         attr->la_projid  = i_projid_read(inode);
2726         attr->la_flags   = ll_inode_to_ext_flags(inode->i_flags);
2727         attr->la_nlink   = inode->i_nlink;
2728         attr->la_rdev    = inode->i_rdev;
2729         attr->la_blksize = 1 << inode->i_blkbits;
2730         attr->la_blkbits = inode->i_blkbits;
2731         /*
2732          * Ext4 did not transfer inherit flags from raw inode
2733          * to inode flags, and ext4 internally test raw inode
2734          * @i_flags directly. Instead of patching ext4, we do it here.
2735          */
2736         if (LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL)
2737                 attr->la_flags |= LUSTRE_PROJINHERIT_FL;
2738 }
2739
2740 static int osd_dirent_count(const struct lu_env *env, struct dt_object *dt,
2741                             u64 *count)
2742 {
2743         struct osd_object *obj = osd_dt_obj(dt);
2744         const struct dt_it_ops *iops;
2745         struct dt_it *it;
2746         int rc;
2747
2748         ENTRY;
2749
2750         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
2751         LASSERT(fid_is_namespace_visible(lu_object_fid(&obj->oo_dt.do_lu)));
2752
2753         if (obj->oo_dirent_count != LU_DIRENT_COUNT_UNSET) {
2754                 *count = obj->oo_dirent_count;
2755                 RETURN(0);
2756         }
2757
2758         /* directory not initialized yet */
2759         if (!dt->do_index_ops) {
2760                 *count = 0;
2761                 RETURN(0);
2762         }
2763
2764         iops = &dt->do_index_ops->dio_it;
2765         it = iops->init(env, dt, LUDA_64BITHASH);
2766         if (IS_ERR(it))
2767                 RETURN(PTR_ERR(it));
2768
2769         rc = iops->load(env, it, 0);
2770         if (rc < 0) {
2771                 if (rc == -ENODATA) {
2772                         rc = 0;
2773                         *count = 0;
2774                 }
2775                 GOTO(out, rc);
2776         }
2777         if (rc > 0)
2778                 rc = iops->next(env, it);
2779
2780         for (*count = 0; rc == 0 || rc == -ESTALE; rc = iops->next(env, it)) {
2781                 if (rc == -ESTALE)
2782                         continue;
2783
2784                 if (iops->key_size(env, it) == 0)
2785                         continue;
2786
2787                 (*count)++;
2788         }
2789         if (rc == 1) {
2790                 obj->oo_dirent_count = *count;
2791                 rc = 0;
2792         }
2793 out:
2794         iops->put(env, it);
2795         iops->fini(env, it);
2796
2797         RETURN(rc);
2798 }
2799
2800 static int osd_attr_get(const struct lu_env *env, struct dt_object *dt,
2801                         struct lu_attr *attr)
2802 {
2803         struct osd_object *obj = osd_dt_obj(dt);
2804         int rc = 0;
2805
2806         if (unlikely(!dt_object_exists(dt)))
2807                 return -ENOENT;
2808         if (unlikely(obj->oo_destroyed))
2809                 return -ENOENT;
2810
2811         LASSERT(!dt_object_remote(dt));
2812         LINVRNT(osd_invariant(obj));
2813
2814         spin_lock(&obj->oo_guard);
2815         osd_inode_getattr(env, obj->oo_inode, attr);
2816         if (obj->oo_lma_flags & LUSTRE_ORPHAN_FL) {
2817                 attr->la_valid |= LA_FLAGS;
2818                 attr->la_flags |= LUSTRE_ORPHAN_FL;
2819         }
2820         if (obj->oo_lma_flags & LUSTRE_ENCRYPT_FL) {
2821                 attr->la_valid |= LA_FLAGS;
2822                 attr->la_flags |= LUSTRE_ENCRYPT_FL;
2823         }
2824         spin_unlock(&obj->oo_guard);
2825
2826         if (S_ISDIR(obj->oo_inode->i_mode) &&
2827             fid_is_namespace_visible(lu_object_fid(&dt->do_lu)))
2828                 rc = osd_dirent_count(env, dt, &attr->la_dirent_count);
2829
2830         return rc;
2831 }
2832
2833 static int osd_declare_attr_qid(const struct lu_env *env,
2834                                 struct osd_object *obj,
2835                                 struct osd_thandle *oh, long long bspace,
2836                                 qid_t old_id, qid_t new_id, bool enforce,
2837                                 unsigned int type)
2838 {
2839         int rc;
2840         struct osd_thread_info *info = osd_oti_get(env);
2841         struct lquota_id_info  *qi = &info->oti_qi;
2842
2843         qi->lqi_type = type;
2844         /* inode accounting */
2845         qi->lqi_is_blk = false;
2846
2847         /* one more inode for the new id ... */
2848         qi->lqi_id.qid_uid = new_id;
2849         qi->lqi_space      = 1;
2850         /* Reserve credits for the new id */
2851         rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
2852         if (rc == -EDQUOT || rc == -EINPROGRESS)
2853                 rc = 0;
2854         if (rc)
2855                 RETURN(rc);
2856
2857         /* and one less inode for the current id */
2858         qi->lqi_id.qid_uid = old_id;
2859         qi->lqi_space = -1;
2860         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2861         if (rc == -EDQUOT || rc == -EINPROGRESS)
2862                 rc = 0;
2863         if (rc)
2864                 RETURN(rc);
2865
2866         /* block accounting */
2867         qi->lqi_is_blk = true;
2868
2869         /* more blocks for the new id ... */
2870         qi->lqi_id.qid_uid = new_id;
2871         qi->lqi_space      = bspace;
2872         /*
2873          * Credits for the new uid has been reserved, re-use "obj"
2874          * to save credit reservation.
2875          */
2876         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2877         if (rc == -EDQUOT || rc == -EINPROGRESS)
2878                 rc = 0;
2879         if (rc)
2880                 RETURN(rc);
2881
2882         /* and finally less blocks for the current uid */
2883         qi->lqi_id.qid_uid = old_id;
2884         qi->lqi_space      = -bspace;
2885         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2886         if (rc == -EDQUOT || rc == -EINPROGRESS)
2887                 rc = 0;
2888
2889         RETURN(rc);
2890 }
2891
2892 static int osd_declare_attr_set(const struct lu_env *env,
2893                                 struct dt_object *dt,
2894                                 const struct lu_attr *attr,
2895                                 struct thandle *handle)
2896 {
2897         struct osd_thandle *oh;
2898         struct osd_object *obj;
2899         qid_t uid;
2900         qid_t gid;
2901         long long bspace;
2902         int rc = 0;
2903         bool enforce;
2904
2905         ENTRY;
2906
2907         LASSERT(dt != NULL);
2908         LASSERT(handle != NULL);
2909
2910         obj = osd_dt_obj(dt);
2911         LASSERT(osd_invariant(obj));
2912
2913         oh = container_of(handle, struct osd_thandle, ot_super);
2914         LASSERT(oh->ot_handle == NULL);
2915
2916         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
2917                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2918
2919         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2920                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2921
2922         if (attr == NULL || obj->oo_inode == NULL)
2923                 RETURN(rc);
2924
2925         bspace   = obj->oo_inode->i_blocks << 9;
2926         bspace   = toqb(bspace);
2927
2928         /*
2929          * Changing ownership is always preformed by super user, it should not
2930          * fail with EDQUOT unless required explicitly.
2931          *
2932          * We still need to call the osd_declare_qid() to calculate the journal
2933          * credits for updating quota accounting files and to trigger quota
2934          * space adjustment once the operation is completed.
2935          */
2936         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
2937                 /* USERQUOTA */
2938                 uid = i_uid_read(obj->oo_inode);
2939                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
2940                 rc = osd_declare_attr_qid(env, obj, oh, bspace, uid,
2941                                           attr->la_uid, enforce, USRQUOTA);
2942                 if (rc)
2943                         RETURN(rc);
2944
2945                 gid = i_gid_read(obj->oo_inode);
2946                 CDEBUG(D_QUOTA, "declare uid %d -> %d gid %d -> %d\n", uid,
2947                        attr->la_uid, gid, attr->la_gid);
2948                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
2949                 rc = osd_declare_attr_qid(env, obj, oh, bspace, gid,
2950                                           attr->la_gid, enforce, GRPQUOTA);
2951                 if (rc)
2952                         RETURN(rc);
2953
2954         }
2955 #ifdef HAVE_PROJECT_QUOTA
2956         if (attr->la_valid & LA_PROJID) {
2957                 __u32 projid = i_projid_read(obj->oo_inode);
2958
2959                 enforce = (attr->la_valid & LA_PROJID) &&
2960                                         (attr->la_projid != projid);
2961                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2962                                           (qid_t)projid, (qid_t)attr->la_projid,
2963                                           enforce, PRJQUOTA);
2964                 if (rc)
2965                         RETURN(rc);
2966         }
2967 #endif
2968         /* punch must be aware we are dealing with an encrypted file */
2969         if (attr->la_valid & LA_FLAGS && attr->la_flags & LUSTRE_ENCRYPT_FL)
2970                 obj->oo_lma_flags |= LUSTRE_ENCRYPT_FL;
2971
2972         RETURN(rc);
2973 }
2974
2975 static int osd_inode_setattr(const struct lu_env *env,
2976                              struct inode *inode, const struct lu_attr *attr)
2977 {
2978         __u64 bits = attr->la_valid;
2979
2980         /* Only allow set size for regular file */
2981         if (!S_ISREG(inode->i_mode))
2982                 bits &= ~(LA_SIZE | LA_BLOCKS);
2983
2984         if (bits == 0)
2985                 return 0;
2986
2987         if (bits & LA_ATIME)
2988                 inode->i_atime = osd_inode_time(inode, attr->la_atime);
2989         if (bits & LA_CTIME)
2990                 inode->i_ctime = osd_inode_time(inode, attr->la_ctime);
2991         if (bits & LA_MTIME)
2992                 inode->i_mtime = osd_inode_time(inode, attr->la_mtime);
2993         if (bits & LA_SIZE) {
2994                 spin_lock(&inode->i_lock);
2995                 LDISKFS_I(inode)->i_disksize = attr->la_size;
2996                 i_size_write(inode, attr->la_size);
2997                 spin_unlock(&inode->i_lock);
2998         }
2999
3000         /*
3001          * OSD should not change "i_blocks" which is used by quota.
3002          * "i_blocks" should be changed by ldiskfs only.
3003          */
3004         if (bits & LA_MODE)
3005                 inode->i_mode = (inode->i_mode & S_IFMT) |
3006                                 (attr->la_mode & ~S_IFMT);
3007         if (bits & LA_UID)
3008                 i_uid_write(inode, attr->la_uid);
3009         if (bits & LA_GID)
3010                 i_gid_write(inode, attr->la_gid);
3011         if (bits & LA_PROJID)
3012                 i_projid_write(inode, attr->la_projid);
3013         if (bits & LA_NLINK)
3014                 set_nlink(inode, attr->la_nlink);
3015         if (bits & LA_RDEV)
3016                 inode->i_rdev = attr->la_rdev;
3017
3018         if (bits & LA_FLAGS) {
3019                 /* always keep S_NOCMTIME */
3020                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
3021                                  S_NOCMTIME;
3022 #if defined(S_ENCRYPTED)
3023                 /* Always remove S_ENCRYPTED, because ldiskfs must not be
3024                  * aware of encryption status. It is just stored into LMA
3025                  * so that it can be forwared to client side.
3026                  */
3027                 inode->i_flags &= ~S_ENCRYPTED;
3028 #endif
3029                 /*
3030                  * Ext4 did not transfer inherit flags from
3031                  * @inode->i_flags to raw inode i_flags when writing
3032                  * flags, we do it explictly here.
3033                  */
3034                 if (attr->la_flags & LUSTRE_PROJINHERIT_FL)
3035                         LDISKFS_I(inode)->i_flags |= LUSTRE_PROJINHERIT_FL;
3036                 else
3037                         LDISKFS_I(inode)->i_flags &= ~LUSTRE_PROJINHERIT_FL;
3038         }
3039         return 0;
3040 }
3041
3042 #ifdef HAVE_PROJECT_QUOTA
3043 static int osd_transfer_project(struct inode *inode, __u32 projid,
3044                                 struct thandle *handle)
3045 {
3046         struct super_block *sb = inode->i_sb;
3047         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
3048         int err;
3049         kprojid_t kprojid;
3050         struct ldiskfs_iloc iloc;
3051         struct ldiskfs_inode *raw_inode;
3052         struct dquot *transfer_to[LDISKFS_MAXQUOTAS] = { };
3053
3054         if (!ldiskfs_has_feature_project(sb)) {
3055                 LASSERT(__kprojid_val(LDISKFS_I(inode)->i_projid)
3056                         == LDISKFS_DEF_PROJID);
3057                 if (projid != LDISKFS_DEF_PROJID)
3058                         return -EOPNOTSUPP;
3059                 else
3060                         return 0;
3061         }
3062
3063         if (LDISKFS_INODE_SIZE(sb) <= LDISKFS_GOOD_OLD_INODE_SIZE)
3064                 return -EOPNOTSUPP;
3065
3066         kprojid = make_kprojid(&init_user_ns, (projid_t)projid);
3067         if (projid_eq(kprojid, LDISKFS_I(inode)->i_projid))
3068                 return 0;
3069
3070         err = ldiskfs_get_inode_loc(inode, &iloc);
3071         if (err)
3072                 return err;
3073
3074         raw_inode = ldiskfs_raw_inode(&iloc);
3075         if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3076                 struct osd_thandle *oh = container_of(handle,
3077                                                       struct osd_thandle,
3078                                                       ot_super);
3079                 /**
3080                  * try to expand inode size automatically.
3081                  */
3082                 ldiskfs_mark_inode_dirty(oh->ot_handle, inode);
3083                 if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3084                         err = -EOVERFLOW;
3085                         brelse(iloc.bh);
3086                         return err;
3087                 }
3088         }
3089         brelse(iloc.bh);
3090
3091         dquot_initialize(inode);
3092         transfer_to[PRJQUOTA] = dqget(sb, make_kqid_projid(kprojid));
3093         if (transfer_to[PRJQUOTA]) {
3094                 lock_dquot_transfer(inode);
3095                 err = __dquot_transfer(inode, transfer_to);
3096                 unlock_dquot_transfer(inode);
3097                 dqput(transfer_to[PRJQUOTA]);
3098                 if (err)
3099                         return err;
3100         }
3101
3102         return err;
3103 }
3104 #endif
3105
3106 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr,
3107                               struct thandle *handle)
3108 {
3109         int rc;
3110
3111         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
3112             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
3113                 struct iattr iattr;
3114
3115                 CDEBUG(D_QUOTA,
3116                        "executing dquot_transfer inode %ld uid %d -> %d gid %d -> %d\n",
3117                        inode->i_ino, i_uid_read(inode), attr->la_uid,
3118                        i_gid_read(inode), attr->la_gid);
3119
3120                 dquot_initialize(inode);
3121                 iattr.ia_valid = 0;
3122                 if (attr->la_valid & LA_UID)
3123                         iattr.ia_valid |= ATTR_UID;
3124                 if (attr->la_valid & LA_GID)
3125                         iattr.ia_valid |= ATTR_GID;
3126                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3127                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3128
3129                 lock_dquot_transfer(inode);
3130                 rc = dquot_transfer(inode, &iattr);
3131                 unlock_dquot_transfer(inode);
3132                 if (rc) {
3133                         CERROR("%s: quota transfer failed. Is quota enforcement enabled on the ldiskfs filesystem? rc = %d\n",
3134                                osd_ino2name(inode), rc);
3135                         return rc;
3136                 }
3137         }
3138
3139         /* Handle project id transfer here properly */
3140         if (attr->la_valid & LA_PROJID &&
3141             attr->la_projid != i_projid_read(inode)) {
3142                 if (!projid_valid(make_kprojid(&init_user_ns, attr->la_projid)))
3143                         return -EINVAL;
3144 #ifdef HAVE_PROJECT_QUOTA
3145                 rc = osd_transfer_project(inode, attr->la_projid, handle);
3146 #else
3147                 rc = -ENOTSUPP;
3148 #endif
3149                 if (rc) {
3150                         CERROR("%s: quota transfer failed. Is project enforcement enabled on the ldiskfs filesystem? rc = %d\n",
3151                                osd_ino2name(inode), rc);
3152                         return rc;
3153                 }
3154         }
3155         return 0;
3156 }
3157
3158 static int osd_attr_set(const struct lu_env *env,
3159                         struct dt_object *dt,
3160                         const struct lu_attr *attr,
3161                         struct thandle *handle)
3162 {
3163         struct osd_thread_info *info = osd_oti_get(env);
3164         struct osd_object *obj = osd_dt_obj(dt);
3165         struct osd_device *osd = osd_obj2dev(obj);
3166         struct inode *inode;
3167         int rc;
3168
3169         if (!dt_object_exists(dt))
3170                 return -ENOENT;
3171
3172         LASSERT(handle != NULL);
3173         LASSERT(!dt_object_remote(dt));
3174         LASSERT(osd_invariant(obj));
3175
3176         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
3177
3178         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING) &&
3179             !osd_obj2dev(obj)->od_is_ost) {
3180                 struct osd_thread_info *oti = osd_oti_get(env);
3181                 const struct lu_fid *fid0 = lu_object_fid(&dt->do_lu);
3182                 struct lu_fid *fid1 = &oti->oti_fid;
3183                 struct osd_inode_id *id = &oti->oti_id;
3184                 struct iam_path_descr *ipd;
3185                 struct iam_container *bag;
3186                 struct osd_thandle *oh;
3187                 int rc;
3188
3189                 fid_cpu_to_be(fid1, fid0);
3190                 memset(id, 1, sizeof(*id));
3191                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
3192                                   fid0)->oi_dir.od_container;
3193                 ipd = osd_idx_ipd_get(env, bag);
3194                 if (unlikely(ipd == NULL))
3195                         RETURN(-ENOMEM);
3196
3197                 oh = container_of(handle, struct osd_thandle, ot_super);
3198                 rc = iam_update(oh->ot_handle, bag,
3199                                 (const struct iam_key *)fid1,
3200                                 (const struct iam_rec *)id, ipd);
3201                 osd_ipd_put(env, bag, ipd);
3202                 return(rc > 0 ? 0 : rc);
3203         }
3204
3205         inode = obj->oo_inode;
3206
3207         rc = osd_quota_transfer(inode, attr, handle);
3208         if (rc)
3209                 return rc;
3210
3211         spin_lock(&obj->oo_guard);
3212         rc = osd_inode_setattr(env, inode, attr);
3213         spin_unlock(&obj->oo_guard);
3214         if (rc != 0)
3215                 GOTO(out, rc);
3216
3217         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3218
3219         osd_trans_exec_check(env, handle, OSD_OT_ATTR_SET);
3220
3221         if (!(attr->la_valid & LA_FLAGS))
3222                 GOTO(out, rc);
3223
3224         /* If setting LUSTRE_ENCRYPT_FL on an OST object, also set a dummy
3225          * enc ctx xattr, with 2 benefits:
3226          * - setting the LL_XATTR_NAME_ENCRYPTION_CONTEXT xattr internally sets
3227          *   the LDISKFS_ENCRYPT_FL flag on the on-disk inode;
3228          * - it makes e2fsprogs happy to see an enc ctx for an inode that has
3229          *   the LDISKFS_ENCRYPT_FL flag
3230          * We do not need the actual encryption context on OST objects, it is
3231          * only stored on MDT inodes, at file creation time.
3232          */
3233         if (!(LDISKFS_I(obj->oo_inode)->i_flags & LDISKFS_ENCRYPT_FL) &&
3234             attr->la_flags & LUSTRE_ENCRYPT_FL && osd->od_is_ost &&
3235             !OBD_FAIL_CHECK(OBD_FAIL_LFSCK_NO_ENCFLAG)) {
3236                 struct lu_buf buf;
3237
3238                 /* use a dummy enc ctx, fine with e2fsprogs */
3239                 buf.lb_buf = "\xFF";
3240                 buf.lb_len = 1;
3241                 rc = osd_xattr_set(env, dt, &buf,
3242                                    LL_XATTR_NAME_ENCRYPTION_CONTEXT,
3243                                    0, handle);
3244                 if (rc)
3245                         CWARN("%s: set "DFID" enc ctx failed: rc = %d\n",
3246                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
3247                               rc);
3248         }
3249
3250         /* Let's check if there are extra flags need to be set into LMA */
3251         if (attr->la_flags & LUSTRE_LMA_FL_MASKS) {
3252                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
3253
3254                 LASSERT(!obj->oo_pfid_in_lma);
3255
3256                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
3257                                  &info->oti_ost_attrs);
3258                 if (rc)
3259                         GOTO(out, rc);
3260
3261                 if ((lma->lma_incompat & lustre_to_lma_flags(attr->la_flags)) ==
3262                     lustre_to_lma_flags(attr->la_flags))
3263                         /* if lma incompat already has the flags,
3264                          * save a useless call to xattr_set
3265                          */
3266                         GOTO(out, rc = 0);
3267
3268                 lma->lma_incompat |=
3269                         lustre_to_lma_flags(attr->la_flags);
3270                 lustre_lma_swab(lma);
3271
3272                 osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3273
3274                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA,
3275                                      lma, sizeof(*lma), XATTR_REPLACE);
3276                 if (rc != 0)
3277                         CWARN("%s: set "DFID" lma flags %u failed: rc = %d\n",
3278                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
3279                               lma->lma_incompat, rc);
3280                 else
3281                         obj->oo_lma_flags =
3282                                 attr->la_flags & LUSTRE_LMA_FL_MASKS;
3283                 osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
3284         }
3285
3286 out:
3287         return rc;
3288 }
3289
3290 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
3291                                            struct osd_object *obj,
3292                                            const char *name, const int namelen)
3293 {
3294         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
3295 }
3296
3297 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
3298                       umode_t mode, struct dt_allocation_hint *hint,
3299                       struct thandle *th, struct lu_attr *attr)
3300 {
3301         int result;
3302         struct osd_device *osd = osd_obj2dev(obj);
3303         struct osd_thandle *oth;
3304         struct dt_object *parent = NULL;
3305         struct inode *inode;
3306         struct iattr iattr = {
3307                 .ia_valid = ATTR_UID | ATTR_GID |
3308                             ATTR_CTIME | ATTR_MTIME | ATTR_ATIME,
3309                 .ia_ctime.tv_sec = attr->la_ctime,
3310                 .ia_mtime.tv_sec = attr->la_mtime,
3311                 .ia_atime.tv_sec = attr->la_atime,
3312                 .ia_uid = GLOBAL_ROOT_UID,
3313                 .ia_gid = GLOBAL_ROOT_GID,
3314         };
3315         const struct osd_timespec omit = { .tv_nsec = UTIME_OMIT };
3316
3317         if (attr->la_valid & LA_UID)
3318                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3319         if (attr->la_valid & LA_GID)
3320                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3321
3322         LINVRNT(osd_invariant(obj));
3323         LASSERT(obj->oo_inode == NULL);
3324         LASSERT(obj->oo_hl_head == NULL);
3325
3326         if (S_ISDIR(mode) && ldiskfs_pdo) {
3327                 obj->oo_hl_head =
3328                         ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
3329                 if (obj->oo_hl_head == NULL)
3330                         return -ENOMEM;
3331         }
3332
3333         oth = container_of(th, struct osd_thandle, ot_super);
3334         LASSERT(oth->ot_handle->h_transaction != NULL);
3335
3336         if (hint != NULL && hint->dah_parent != NULL &&
3337             !dt_object_remote(hint->dah_parent))
3338                 parent = hint->dah_parent;
3339
3340         /* if a time component is not valid set it to UTIME_OMIT */
3341         if (!(attr->la_valid & LA_CTIME))
3342                 iattr.ia_ctime = omit;
3343         if (!(attr->la_valid & LA_MTIME))
3344                 iattr.ia_mtime = omit;
3345         if (!(attr->la_valid & LA_ATIME))
3346                 iattr.ia_atime = omit;
3347
3348         inode = ldiskfs_create_inode(oth->ot_handle,
3349                                      parent ? osd_dt_obj(parent)->oo_inode :
3350                                               osd_sb(osd)->s_root->d_inode,
3351                                      mode, &iattr);
3352         if (!IS_ERR(inode)) {
3353                 /* Do not update file c/mtime in ldiskfs. */
3354                 inode->i_flags |= S_NOCMTIME;
3355
3356                 /*
3357                  * For new created object, it must be consistent,
3358                  * and it is unnecessary to scrub against it.
3359                  */
3360                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
3361
3362                 obj->oo_inode = inode;
3363                 result = 0;
3364         } else {
3365                 if (obj->oo_hl_head != NULL) {
3366                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
3367                         obj->oo_hl_head = NULL;
3368                 }
3369                 result = PTR_ERR(inode);
3370         }
3371         LINVRNT(osd_invariant(obj));
3372         return result;
3373 }
3374
3375 enum {
3376         OSD_NAME_LEN = 255
3377 };
3378
3379 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
3380                      struct lu_attr *attr,
3381                      struct dt_allocation_hint *hint,
3382                      struct dt_object_format *dof,
3383                      struct thandle *th)
3384 {
3385         int result;
3386         struct osd_thandle *oth;
3387         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX | S_ISGID));
3388
3389         LASSERT(S_ISDIR(attr->la_mode));
3390
3391         oth = container_of(th, struct osd_thandle, ot_super);
3392         LASSERT(oth->ot_handle->h_transaction != NULL);
3393         if (fid_is_namespace_visible(lu_object_fid(&obj->oo_dt.do_lu)))
3394                 obj->oo_dirent_count = 0;
3395         result = osd_mkfile(info, obj, mode, hint, th, attr);
3396
3397         return result;
3398 }
3399
3400 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
3401                         struct lu_attr *attr,
3402                         struct dt_allocation_hint *hint,
3403                         struct dt_object_format *dof,
3404                         struct thandle *th)
3405 {
3406         int result;
3407         struct osd_thandle *oth;
3408         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
3409
3410         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
3411
3412         LASSERT(S_ISREG(attr->la_mode));
3413
3414         oth = container_of(th, struct osd_thandle, ot_super);
3415         LASSERT(oth->ot_handle->h_transaction != NULL);
3416
3417         result = osd_mkfile(info, obj, mode, hint, th, attr);
3418         if (result == 0) {
3419                 LASSERT(obj->oo_inode != NULL);
3420                 if (feat->dif_flags & DT_IND_VARKEY)
3421                         result = iam_lvar_create(obj->oo_inode,
3422                                                  feat->dif_keysize_max,
3423                                                  feat->dif_ptrsize,
3424                                                  feat->dif_recsize_max,
3425                                                  oth->ot_handle);
3426                 else
3427                         result = iam_lfix_create(obj->oo_inode,
3428                                                  feat->dif_keysize_max,
3429                                                  feat->dif_ptrsize,
3430                                                  feat->dif_recsize_max,
3431                                                  oth->ot_handle);
3432         }
3433         return result;
3434 }
3435
3436 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
3437                      struct lu_attr *attr,
3438                      struct dt_allocation_hint *hint,
3439                      struct dt_object_format *dof,
3440                      struct thandle *th)
3441 {
3442         LASSERT(S_ISREG(attr->la_mode));
3443         return osd_mkfile(info, obj, (attr->la_mode &
3444                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3445                           attr);
3446 }
3447
3448 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
3449                      struct lu_attr *attr,
3450                      struct dt_allocation_hint *hint,
3451                      struct dt_object_format *dof,
3452                      struct thandle *th)
3453 {
3454         LASSERT(S_ISLNK(attr->la_mode));
3455         return osd_mkfile(info, obj, (attr->la_mode &
3456                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3457                           attr);
3458 }
3459
3460 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
3461                      struct lu_attr *attr,
3462                      struct dt_allocation_hint *hint,
3463                      struct dt_object_format *dof,
3464                      struct thandle *th)
3465 {
3466         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
3467         int result;
3468
3469         LINVRNT(osd_invariant(obj));
3470         LASSERT(obj->oo_inode == NULL);
3471         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
3472                 S_ISFIFO(mode) || S_ISSOCK(mode));
3473
3474         result = osd_mkfile(info, obj, mode, hint, th, attr);
3475         if (result == 0) {
3476                 LASSERT(obj->oo_inode != NULL);
3477                 /*
3478                  * This inode should be marked dirty for i_rdev.  Currently
3479                  * that is done in the osd_attr_init().
3480                  */
3481                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
3482                                    attr->la_rdev);
3483         }
3484         LINVRNT(osd_invariant(obj));
3485         return result;
3486 }
3487
3488 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
3489                               struct lu_attr *,
3490                               struct dt_allocation_hint *hint,
3491                               struct dt_object_format *dof,
3492                               struct thandle *);
3493
3494 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
3495 {
3496         osd_obj_type_f result;
3497
3498         switch (type) {
3499         case DFT_DIR:
3500                 result = osd_mkdir;
3501                 break;
3502         case DFT_REGULAR:
3503                 result = osd_mkreg;
3504                 break;
3505         case DFT_SYM:
3506                 result = osd_mksym;
3507                 break;
3508         case DFT_NODE:
3509                 result = osd_mknod;
3510                 break;
3511         case DFT_INDEX:
3512                 result = osd_mk_index;
3513                 break;
3514
3515         default:
3516                 LBUG();
3517                 break;
3518         }
3519         return result;
3520 }
3521
3522 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
3523                         struct dt_object *parent, struct dt_object *child,
3524                         umode_t child_mode)
3525 {
3526         LASSERT(ah);
3527
3528         ah->dah_parent = parent;
3529
3530         if (parent != NULL && !dt_object_remote(parent)) {
3531                 /* will help to find FID->ino at dt_insert("..") */
3532                 struct osd_object *pobj = osd_dt_obj(parent);
3533
3534                 osd_idc_find_and_init(env, osd_obj2dev(pobj), pobj);
3535         }
3536 }
3537
3538 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
3539                           struct lu_attr *attr, struct dt_object_format *dof,
3540                           struct thandle *handle)
3541 {
3542         struct inode *inode = obj->oo_inode;
3543         __u64 valid = attr->la_valid;
3544         int result;
3545
3546         attr->la_valid &= ~(LA_TYPE | LA_MODE);
3547
3548         if (dof->dof_type != DFT_NODE)
3549                 attr->la_valid &= ~LA_RDEV;
3550         if ((valid & LA_ATIME) && (attr->la_atime == inode->i_atime.tv_sec))
3551                 attr->la_valid &= ~LA_ATIME;
3552         if ((valid & LA_CTIME) && (attr->la_ctime == inode->i_ctime.tv_sec))
3553                 attr->la_valid &= ~LA_CTIME;
3554         if ((valid & LA_MTIME) && (attr->la_mtime == inode->i_mtime.tv_sec))
3555                 attr->la_valid &= ~LA_MTIME;
3556
3557         result = osd_quota_transfer(inode, attr, handle);
3558         if (result)
3559                 return;
3560
3561         if (attr->la_valid != 0) {
3562                 result = osd_inode_setattr(info->oti_env, inode, attr);
3563                 /*
3564                  * The osd_inode_setattr() should always succeed here.  The
3565                  * only error that could be returned is EDQUOT when we are
3566                  * trying to change the UID or GID of the inode. However, this
3567                  * should not happen since quota enforcement is no longer
3568                  * enabled on ldiskfs (lquota takes care of it).
3569                  */
3570                 LASSERTF(result == 0, "%d\n", result);
3571                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3572         }
3573
3574         attr->la_valid = valid;
3575 }
3576
3577 /**
3578  * Helper function for osd_create()
3579  *
3580  * \retval 0, on success
3581  */
3582 static int __osd_create(struct osd_thread_info *info, struct osd_object *obj,
3583                         struct lu_attr *attr, struct dt_allocation_hint *hint,
3584                         struct dt_object_format *dof, struct thandle *th)
3585 {
3586         int result;
3587         __u32 umask;
3588
3589         osd_trans_exec_op(info->oti_env, th, OSD_OT_CREATE);
3590
3591         /* we drop umask so that permissions we pass are not affected */
3592         umask = current->fs->umask;
3593         current->fs->umask = 0;
3594
3595         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
3596                                                   th);
3597         if (likely(obj->oo_inode != NULL)) {
3598                 LASSERT(obj->oo_inode->i_state & I_NEW);
3599
3600                 /*
3601                  * Unlock the inode before attr initialization to avoid
3602                  * unnecessary dqget operations. LU-6378
3603                  */
3604                 unlock_new_inode(obj->oo_inode);
3605         }
3606
3607         if (likely(result == 0)) {
3608                 osd_attr_init(info, obj, attr, dof, th);
3609                 osd_object_init0(obj);
3610         }
3611
3612         /* restore previous umask value */
3613         current->fs->umask = umask;
3614
3615         osd_trans_exec_check(info->oti_env, th, OSD_OT_CREATE);
3616
3617         return result;
3618 }
3619
3620 /**
3621  * Helper function for osd_create()
3622  *
3623  * \retval 0, on success
3624  */
3625 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
3626                            const struct lu_fid *fid, struct thandle *th)
3627 {
3628         struct osd_thread_info *info = osd_oti_get(env);
3629         struct osd_inode_id    *id   = &info->oti_id;
3630         struct osd_device      *osd  = osd_obj2dev(obj);
3631         struct osd_thandle     *oh;
3632         int rc;
3633
3634         LASSERT(obj->oo_inode != NULL);
3635
3636         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_OI_ENOSPC))
3637                 return -ENOSPC;
3638
3639         oh = container_of(th, struct osd_thandle, ot_super);
3640         LASSERT(oh->ot_handle);
3641         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3642
3643         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
3644         rc = osd_oi_insert(info, osd, fid, id, oh->ot_handle,
3645                            OI_CHECK_FLD, NULL);
3646         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP) && osd->od_is_ost) {
3647                 struct lu_fid next_fid = *fid;
3648
3649                 /* insert next object in advance, and map to the same inode */
3650                 next_fid.f_oid++;
3651                 if (next_fid.f_oid != 0) {
3652                         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3653                         osd_oi_insert(info, osd, &next_fid, id, oh->ot_handle,
3654                                       OI_CHECK_FLD, NULL);
3655                         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3656                 }
3657         }
3658
3659         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3660
3661         return rc;
3662 }
3663
3664 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
3665                    u64 seq, struct lu_seq_range *range)
3666 {
3667         struct seq_server_site *ss = osd_seq_site(osd);
3668
3669         if (fid_seq_is_idif(seq)) {
3670                 fld_range_set_ost(range);
3671                 range->lsr_index = idif_ost_idx(seq);
3672                 return 0;
3673         }
3674
3675         if (!fid_seq_in_fldb(seq)) {
3676                 fld_range_set_mdt(range);
3677                 if (ss != NULL)
3678                         /*
3679                          * FIXME: If ss is NULL, it suppose not get lsr_index
3680                          * at all
3681                          */
3682                         range->lsr_index = ss->ss_node_id;
3683                 return 0;
3684         }
3685
3686         LASSERT(ss != NULL);
3687         fld_range_set_any(range);
3688         /* OSD will only do local fld lookup */
3689         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
3690 }
3691
3692 static int osd_declare_create(const struct lu_env *env, struct dt_object *dt,
3693                               struct lu_attr *attr,
3694                               struct dt_allocation_hint *hint,
3695                               struct dt_object_format *dof,
3696                               struct thandle *handle)
3697 {
3698         struct osd_thandle *oh;
3699         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3700         int credits;
3701         int rc;
3702
3703         ENTRY;
3704
3705         LASSERT(handle != NULL);
3706
3707         oh = container_of(handle, struct osd_thandle, ot_super);
3708         LASSERT(oh->ot_handle == NULL);
3709
3710         /*
3711          * EA object consumes more credits than regular object: osd_mk_index
3712          * vs. osd_mkreg: osd_mk_index will create 2 blocks for root_node and
3713          * leaf_node, could involves the block, block bitmap, groups, GDT
3714          * change for each block, so add 4 * 2 credits in that case.
3715          *
3716          * The default ACL initialization may consume an additional 16 blocks
3717          */
3718         credits = osd_dto_credits_noquota[DTO_OBJECT_CREATE] +
3719                   ((dof->dof_type == DFT_INDEX) ? 4 * 2 : 0);
3720
3721         /**
3722          * While ldiskfs_new_inode() calls ldiskfs_init_acl() we have to add
3723          * credits for possible default ACL creation in new inode
3724          */
3725         if (hint && hint->dah_acl_len)
3726                 credits += osd_calc_bkmap_credits(sb, NULL, 0, -1,
3727                                 (hint->dah_acl_len + sb->s_blocksize - 1) >>
3728                                 sb->s_blocksize_bits);
3729
3730         osd_trans_declare_op(env, oh, OSD_OT_CREATE, credits);
3731
3732         /*
3733          * Reuse idle OI block may cause additional one OI block
3734          * to be changed.
3735          */
3736         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3737                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3738         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP))
3739                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3740                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3741
3742         /* will help to find FID->ino mapping at dt_insert() */
3743         rc = osd_idc_find_and_init(env, osd_obj2dev(osd_dt_obj(dt)),
3744                                    osd_dt_obj(dt));
3745         if (rc != 0)
3746                 RETURN(rc);
3747
3748         if (!attr)
3749                 RETURN(0);
3750
3751         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid,
3752                                    attr->la_projid, 1, oh, osd_dt_obj(dt),
3753                                    NULL, OSD_QID_INODE);
3754         if (rc != 0)
3755                 RETURN(rc);
3756
3757         RETURN(rc);
3758 }
3759
3760 /**
3761  * Called to destroy on-disk representation of the object
3762  *
3763  * Concurrency: must be locked
3764  */
3765 static int osd_declare_destroy(const struct lu_env *env, struct dt_object *dt,
3766                                struct thandle *th)
3767 {
3768         struct osd_object *obj = osd_dt_obj(dt);
3769         struct inode *inode = obj->oo_inode;
3770         struct osd_thandle *oh;
3771         int rc;
3772
3773         ENTRY;
3774
3775         if (inode == NULL)
3776                 RETURN(-ENOENT);
3777
3778         oh = container_of(th, struct osd_thandle, ot_super);
3779         LASSERT(oh->ot_handle == NULL);
3780
3781         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
3782                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
3783
3784         /* For removing agent entry */
3785         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu))
3786                 oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
3787
3788         /*
3789          * Recycle idle OI leaf may cause additional three OI blocks
3790          * to be changed.
3791          */
3792         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3793                 osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3794                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
3795         /* one less inode */
3796         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3797                                    i_projid_read(inode), -1, oh, obj, NULL,
3798                                    OSD_QID_INODE);
3799         if (rc)
3800                 RETURN(rc);
3801         /* data to be truncated */
3802         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3803                                    i_projid_read(inode), 0, oh, obj, NULL,
3804                                    OSD_QID_BLK);
3805         if (rc)
3806                 RETURN(rc);
3807
3808         /*
3809          * will help to find FID->ino when this object is being
3810          * added to PENDING
3811          */
3812         rc = osd_idc_find_and_init(env, osd_obj2dev(obj), obj);
3813
3814         RETURN(rc);
3815 }
3816
3817 static int osd_destroy(const struct lu_env *env, struct dt_object *dt,
3818                        struct thandle *th)
3819 {
3820         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3821         struct osd_object *obj = osd_dt_obj(dt);
3822         struct inode *inode = obj->oo_inode;
3823         struct osd_device *osd = osd_obj2dev(obj);
3824         struct osd_thandle *oh;
3825         int result;
3826
3827         ENTRY;
3828
3829         oh = container_of(th, struct osd_thandle, ot_super);
3830         LASSERT(oh->ot_handle);
3831         LASSERT(inode);
3832         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
3833
3834         if (unlikely(fid_is_acct(fid)))
3835                 RETURN(-EPERM);
3836
3837         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu)) {
3838                 result = osd_delete_from_remote_parent(env, osd, obj, oh, true);
3839                 if (result != 0)
3840                         CERROR("%s: remove agent entry "DFID": rc = %d\n",
3841                                osd_name(osd), PFID(fid), result);
3842         }
3843
3844         if (S_ISDIR(inode->i_mode)) {
3845                 if (inode->i_nlink > 2)
3846                         CERROR("%s: directory "DFID" ino %lu link count is %u at unlink. run e2fsck to repair\n",
3847                                osd_name(osd), PFID(fid), inode->i_ino,
3848                                inode->i_nlink);
3849
3850                 spin_lock(&obj->oo_guard);
3851                 clear_nlink(inode);
3852                 spin_unlock(&obj->oo_guard);
3853                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3854         }
3855
3856         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
3857
3858         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
3859
3860         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3861                 result = osd_oi_delete(osd_oti_get(env), osd, fid,
3862                                        oh->ot_handle, OI_CHECK_FLD);
3863
3864         osd_trans_exec_check(env, th, OSD_OT_DESTROY);
3865         /* XXX: add to ext3 orphan list */
3866         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
3867
3868         /* not needed in the cache anymore */
3869         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
3870         obj->oo_destroyed = 1;
3871
3872         RETURN(0);
3873 }
3874
3875 /**
3876  * Put the fid into lustre_mdt_attrs, and then place the structure
3877  * inode's ea. This fid should not be altered during the life time
3878  * of the inode.
3879  *
3880  * \retval +ve, on success
3881  * \retval -ve, on error
3882  *
3883  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
3884  */
3885 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
3886                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
3887 {
3888         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
3889         struct lustre_mdt_attrs *lma = &loa->loa_lma;
3890         int rc;
3891
3892         ENTRY;
3893
3894         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
3895                 RETURN(0);
3896
3897         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_OST_EA_FID_SET))
3898                 rc = -ENOMEM;
3899
3900         lustre_loa_init(loa, fid, compat, incompat);
3901         lustre_loa_swab(loa, false);
3902
3903         /*
3904          * For the OST device with 256 bytes inode size by default,
3905          * the PFID EA will be stored together with LMA EA to avoid
3906          * performance trouble. Otherwise the PFID EA can be stored
3907          * independently. LU-8998
3908          */
3909         if ((compat & LMAC_FID_ON_OST) &&
3910             LDISKFS_INODE_SIZE(inode->i_sb) <= 256)
3911                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3912                                      sizeof(*loa), XATTR_CREATE);
3913         else
3914                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3915                                      sizeof(*lma), XATTR_CREATE);
3916         /*
3917          * LMA may already exist, but we need to check that all the
3918          * desired compat/incompat flags have been added.
3919          */
3920         if (unlikely(rc == -EEXIST)) {
3921                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
3922                                      XATTR_NAME_LMA, (void *)loa, sizeof(*loa));
3923                 if (rc < 0)
3924                         RETURN(rc);
3925
3926                 if (rc < sizeof(*lma))
3927                         RETURN(-EINVAL);
3928
3929                 lustre_loa_swab(loa, true);
3930                 if (lu_fid_eq(fid, &lma->lma_self_fid) &&
3931                     ((compat == 0 && incompat == 0) ||
3932                      (!(~lma->lma_compat & compat) &&
3933                       !(~lma->lma_incompat & incompat))))
3934                         RETURN(0);
3935
3936                 lma->lma_self_fid = *fid;
3937                 lma->lma_compat |= compat;
3938                 lma->lma_incompat |= incompat;
3939                 if (rc == sizeof(*lma)) {
3940                         lustre_lma_swab(lma);
3941                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3942                                              sizeof(*lma), XATTR_REPLACE);
3943                 } else {
3944                         lustre_loa_swab(loa, false);
3945                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3946                                              sizeof(*loa), XATTR_REPLACE);
3947                 }
3948         }
3949
3950         RETURN(rc);
3951 }
3952
3953 /**
3954  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
3955  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
3956  * To have compatilibility with 1.8 ldiskfs driver we need to have
3957  * magic number at start of fid data.
3958  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
3959  * its inmemory API.
3960  */
3961 static void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
3962                                          const struct lu_fid *fid)
3963 {
3964         if (!fid_is_namespace_visible(fid) ||
3965             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
3966                 param->edp_magic = 0;
3967                 return;
3968         }
3969
3970         param->edp_magic = LDISKFS_LUFID_MAGIC;
3971         param->edp_len =  sizeof(struct lu_fid) + 1;
3972         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
3973 }
3974
3975 /**
3976  * Try to read the fid from inode ea into dt_rec.
3977  *
3978  * \param fid object fid.
3979  *
3980  * \retval 0 on success
3981  */
3982 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
3983                           __u32 ino, struct lu_fid *fid,
3984                           struct osd_inode_id *id)
3985 {
3986         struct osd_thread_info *info  = osd_oti_get(env);
3987         struct inode *inode;
3988
3989         ENTRY;
3990
3991         osd_id_gen(id, ino, OSD_OII_NOGEN);
3992         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
3993         if (IS_ERR(inode))
3994                 RETURN(PTR_ERR(inode));
3995
3996         iput(inode);
3997         RETURN(0);
3998 }
3999
4000 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
4001                                         struct inode *dir,
4002                                         struct inode *parent_dir,
4003                                         const struct lu_fid *dot_fid,
4004                                         const struct lu_fid *dot_dot_fid,
4005                                         struct osd_thandle *oth)
4006 {
4007         struct ldiskfs_dentry_param *dot_ldp;
4008         struct ldiskfs_dentry_param *dot_dot_ldp;
4009         __u32 saved_nlink = dir->i_nlink;
4010         int rc;
4011
4012         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_DOTDOT_ENOSPC))
4013                 return -ENOSPC;
4014
4015         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
4016         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
4017
4018         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
4019         dot_ldp->edp_magic = 0;
4020
4021         rc = ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
4022                                     dir, dot_ldp, dot_dot_ldp);
4023         /*
4024          * The ldiskfs_add_dot_dotdot() may dir->i_nlink as 2, then
4025          * the subseqent ref_add() will increase the dir->i_nlink
4026          * as 3. That is incorrect for new created directory.
4027          *
4028          * It looks like hack, because we want to make the OSD API
4029          * to be order-independent for new created directory object
4030          * between dt_insert(..) and ref_add() operations.
4031          *
4032          * Here, we only restore the in-RAM dir-inode's nlink attr,
4033          * becuase if the nlink attr is not 2, then there will be
4034          * ref_add() called following the dt_insert(..), such call
4035          * will make both the in-RAM and on-disk dir-inode's nlink
4036          * attr to be set as 2. LU-7447
4037          */
4038         set_nlink(dir, saved_nlink);
4039         return rc;
4040 }
4041
4042 /**
4043  * Create an local agent inode for remote entry
4044  */
4045 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
4046                                                   struct osd_device *osd,
4047                                                   struct osd_object *pobj,
4048                                                   const struct lu_fid *fid,
4049                                                   __u32 type,
4050                                                   struct thandle *th)
4051 {
4052         struct osd_thread_info *info = osd_oti_get(env);
4053         struct inode *local;
4054         struct osd_thandle *oh;
4055         struct iattr iattr = {
4056                 .ia_valid = ATTR_UID | ATTR_GID |
4057                             ATTR_CTIME | ATTR_MTIME | ATTR_ATIME,
4058                 .ia_ctime.tv_nsec = UTIME_OMIT,
4059                 .ia_mtime.tv_nsec = UTIME_OMIT,
4060                 .ia_atime.tv_nsec = UTIME_OMIT,
4061                 .ia_uid = GLOBAL_ROOT_UID,
4062                 .ia_gid = GLOBAL_ROOT_GID,
4063         };
4064         int rc;
4065
4066         ENTRY;
4067
4068         LASSERT(th);
4069         oh = container_of(th, struct osd_thandle, ot_super);
4070         LASSERT(oh->ot_handle->h_transaction != NULL);
4071
4072         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode,
4073                                      type, &iattr);
4074         if (IS_ERR(local)) {
4075                 CERROR("%s: create local error %d\n", osd_name(osd),
4076                        (int)PTR_ERR(local));
4077                 RETURN(local);
4078         }
4079
4080         /*
4081          * restore i_gid in case S_ISGID is set, we will inherit S_ISGID and set
4082          * correct gid on remote file, not agent here
4083          */
4084         local->i_gid = current_fsgid();
4085         ldiskfs_set_inode_state(local, LDISKFS_STATE_LUSTRE_NOSCRUB);
4086
4087         /* e2fsck doesn't like empty symlinks.  Store remote FID as symlink.
4088          * That gives e2fsck something to look at and be happy, and allows
4089          * debugging if we need to determine where this symlink came from.
4090          */
4091         if (S_ISLNK(type)) {
4092                 BUILD_BUG_ON(LDISKFS_N_BLOCKS * 4 < FID_LEN + 1);
4093                 ldiskfs_clear_inode_flag(local, LDISKFS_INODE_EXTENTS);
4094                 rc = scnprintf((char *)LDISKFS_I(local)->i_data,
4095                                LDISKFS_N_BLOCKS * 4, DFID, PFID(fid));
4096
4097                 i_size_write(local, rc);
4098                 LDISKFS_I(local)->i_disksize = rc;
4099         }
4100         unlock_new_inode(local);
4101
4102         /* Agent inode should not have project ID */
4103 #ifdef  HAVE_PROJECT_QUOTA
4104         if (LDISKFS_I(pobj->oo_inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
4105             i_projid_read(pobj->oo_inode) != 0) {
4106                 rc = osd_transfer_project(local, 0, th);
4107                 if (rc) {
4108                         CERROR("%s: quota transfer failed:. Is project quota enforcement enabled on the ldiskfs filesystem? rc = %d\n",
4109                                osd_ino2name(local), rc);
4110                         RETURN(ERR_PTR(rc));
4111                 }
4112         }
4113 #endif
4114         /* Set special LMA flag for local agent inode */
4115         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
4116         if (rc != 0) {
4117                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
4118                        osd_name(osd), PFID(fid), rc);
4119                 RETURN(ERR_PTR(rc));
4120         }
4121
4122         if (!S_ISDIR(type))
4123                 RETURN(local);
4124
4125         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode, fid,
4126                                          lu_object_fid(&pobj->oo_dt.do_lu),
4127                                          oh);
4128         if (rc != 0) {
4129                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
4130                         osd_name(osd), PFID(fid), rc);
4131                 RETURN(ERR_PTR(rc));
4132         }
4133
4134         RETURN(local);
4135 }
4136
4137 /**
4138  * when direntry is deleted, we have to take care of possible agent inode
4139  * referenced by that. unfortunately we can't do this at that point:
4140  * iget() within a running transaction leads to deadlock and we better do
4141  * not call that every delete declaration to save performance. so we put
4142  * a potention agent inode on a list and process that once the transaction
4143  * is over. Notice it's not any worse in terms of real orphans as regular
4144  * object destroy doesn't put inodes on the on-disk orphan list. this should
4145  * be addressed separately
4146  */
4147 static int osd_schedule_agent_inode_removal(const struct lu_env *env,
4148                                             struct osd_thandle *oh,
4149                                             __u32 ino)
4150 {
4151         struct osd_device *osd = osd_dt_dev(oh->ot_super.th_dev);
4152         struct osd_obj_orphan *oor;
4153
4154         OBD_ALLOC_PTR(oor);
4155         if (oor == NULL)
4156                 return -ENOMEM;
4157
4158         oor->oor_ino = ino;
4159         oor->oor_env = (struct lu_env *)env;
4160         spin_lock(&osd->od_osfs_lock);
4161         list_add(&oor->oor_list, &osd->od_orphan_list);
4162         spin_unlock(&osd->od_osfs_lock);
4163
4164         oh->ot_remove_agents = 1;
4165
4166         return 0;
4167
4168 }
4169
4170 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
4171                                                 struct osd_device *osd)
4172 {
4173         struct osd_thread_info *info = osd_oti_get(env);
4174         struct osd_obj_orphan *oor, *tmp;
4175         struct osd_inode_id id;
4176         LIST_HEAD(list);
4177         struct inode *inode;
4178         struct lu_fid fid;
4179         handle_t *jh;
4180         __u32 ino;
4181
4182         spin_lock(&osd->od_osfs_lock);
4183         list_for_each_entry_safe(oor, tmp, &osd->od_orphan_list, oor_list) {
4184                 if (oor->oor_env == env)
4185                         list_move(&oor->oor_list, &list);
4186         }
4187         spin_unlock(&osd->od_osfs_lock);
4188
4189         list_for_each_entry_safe(oor, tmp, &list, oor_list) {
4190
4191                 ino = oor->oor_ino;
4192
4193                 list_del(&oor->oor_list);
4194                 OBD_FREE_PTR(oor);
4195
4196                 osd_id_gen(&id, ino, OSD_OII_NOGEN);
4197                 inode = osd_iget_fid(info, osd, &id, &fid);
4198                 if (IS_ERR(inode))
4199                         continue;
4200
4201                 if (!osd_remote_fid(env, osd, &fid)) {
4202                         iput(inode);
4203                         continue;
4204                 }
4205
4206                 jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC, 1);
4207                 clear_nlink(inode);
4208                 mark_inode_dirty(inode);
4209                 ldiskfs_journal_stop(jh);
4210                 iput(inode);
4211         }
4212
4213         return 0;
4214 }
4215
4216 /**
4217  * OSD layer object create function for OST objects (b=11826).
4218  *
4219  * The FID is inserted into inode xattr here.
4220  *
4221  * \retval   0, on success
4222  * \retval -ve, on error
4223  */
4224 static int osd_create(const struct lu_env *env, struct dt_object *dt,
4225                       struct lu_attr *attr, struct dt_allocation_hint *hint,
4226                       struct dt_object_format *dof, struct thandle *th)
4227 {
4228         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4229         struct osd_object *obj = osd_dt_obj(dt);
4230         struct osd_thread_info *info = osd_oti_get(env);
4231         int result, on_ost = 0;
4232
4233         ENTRY;
4234
4235         if (dt_object_exists(dt))
4236                 RETURN(-EEXIST);
4237
4238         LINVRNT(osd_invariant(obj));
4239         LASSERT(!dt_object_remote(dt));
4240         LASSERT(osd_is_write_locked(env, obj));
4241         LASSERT(th != NULL);
4242
4243         if (unlikely(fid_is_acct(fid)))
4244                 /*
4245                  * Quota files can't be created from the kernel any more,
4246                  * 'tune2fs -O quota' will take care of creating them
4247                  */
4248                 RETURN(-EPERM);
4249
4250         result = __osd_create(info, obj, attr, hint, dof, th);
4251         if (result == 0) {
4252                 if (fid_is_idif(fid) &&
4253                     !osd_dev(dt->do_lu.lo_dev)->od_index_in_idif) {
4254                         struct lu_fid *tfid = &info->oti_fid;
4255                         struct ost_id *oi   = &info->oti_ostid;
4256
4257                         fid_to_ostid(fid, oi);
4258                         ostid_to_fid(tfid, oi, 0);
4259                         on_ost = 1;
4260                         result = osd_ea_fid_set(info, obj->oo_inode, tfid,
4261                                                 LMAC_FID_ON_OST, 0);
4262                 } else {
4263                         on_ost = fid_is_on_ost(info, osd_obj2dev(obj),
4264                                                fid, OI_CHECK_FLD);
4265                         result = osd_ea_fid_set(info, obj->oo_inode, fid,
4266                                                 on_ost ? LMAC_FID_ON_OST : 0,
4267                                                 0);
4268                 }
4269                 if (obj->oo_dt.do_body_ops == &osd_body_ops_new)
4270                         obj->oo_dt.do_body_ops = &osd_body_ops;
4271         }
4272
4273         if (!result && !CFS_FAIL_CHECK(OBD_FAIL_OSD_NO_OI_ENTRY)) {
4274                 struct inode *inode = obj->oo_inode;
4275
4276                 result = __osd_oi_insert(env, obj, fid, th);
4277                 if (result && inode) {
4278                         spin_lock(&obj->oo_guard);
4279                         clear_nlink(inode);
4280                         spin_unlock(&obj->oo_guard);
4281                         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4282                         ldiskfs_set_inode_state(inode,
4283                                                 LDISKFS_STATE_LUSTRE_DESTROY);
4284                         iput(inode);
4285                         obj->oo_inode = NULL;
4286                 }
4287         }
4288
4289         /*
4290          * a small optimization - dt_insert() isn't usually applied
4291          * to OST objects, so we don't need to cache OI mapping for
4292          * OST objects
4293          */
4294         if (result == 0 && on_ost == 0) {
4295                 struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4296
4297                 result = osd_idc_find_and_init(env, osd, obj);
4298                 LASSERT(result == 0);
4299         }
4300
4301         LASSERT(ergo(result == 0,
4302                      dt_object_exists(dt) && !dt_object_remote(dt)));
4303         LINVRNT(osd_invariant(obj));
4304         RETURN(result);
4305 }
4306
4307 static int osd_declare_ref_add(const struct lu_env *env, struct dt_object *dt,
4308                                struct thandle *handle)
4309 {
4310         struct osd_thandle *oh;
4311         int rc;
4312
4313         /* it's possible that object doesn't exist yet */
4314         LASSERT(handle != NULL);
4315
4316         oh = container_of(handle, struct osd_thandle, ot_super);
4317         LASSERT(oh->ot_handle == NULL);
4318
4319         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
4320                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4321
4322         rc = osd_idc_find_and_init(env, osd_dev(dt->do_lu.lo_dev),
4323                                    osd_dt_obj(dt));
4324
4325         return rc;
4326 }
4327
4328 /*
4329  * Concurrency: @dt is write locked.
4330  */
4331 static int osd_ref_add(const struct lu_env *env, struct dt_object *dt,
4332                        struct thandle *th)
4333 {
4334         struct osd_object *obj = osd_dt_obj(dt);
4335         struct inode *inode = obj->oo_inode;
4336         struct osd_thandle *oh;
4337         int rc = 0;
4338
4339         if (!dt_object_exists(dt) || obj->oo_destroyed)
4340                 return -ENOENT;
4341
4342         LINVRNT(osd_invariant(obj));
4343         LASSERT(!dt_object_remote(dt));
4344         LASSERT(osd_is_write_locked(env, obj));
4345         LASSERT(th != NULL);
4346
4347         oh = container_of(th, struct osd_thandle, ot_super);
4348         LASSERT(oh->ot_handle != NULL);
4349
4350         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
4351
4352         CDEBUG(D_INODE, DFID" increase nlink %d\n",
4353                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4354         /*
4355          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
4356          * (65000) subdirectories by storing "1" in i_nlink if the link count
4357          * would otherwise overflow. Directory tranversal tools understand
4358          * that (st_nlink == 1) indicates that the filesystem dose not track
4359          * hard links count on the directory, and will not abort subdirectory
4360          * scanning early once (st_nlink - 2) subdirs have been found.
4361          *
4362          * This also has to properly handle the case of inodes with nlink == 0
4363          * in case they are being linked into the PENDING directory
4364          */
4365         spin_lock(&obj->oo_guard);
4366         if (unlikely(inode->i_nlink == 0))
4367                 /* inc_nlink from 0 may cause WARN_ON */
4368                 set_nlink(inode, 1);
4369         else {
4370                 osd_ldiskfs_inc_count(oh->ot_handle, inode);
4371                 if (!S_ISDIR(inode->i_mode))
4372                         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
4373         }
4374         spin_unlock(&obj->oo_guard);
4375
4376         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4377         LINVRNT(osd_invariant(obj));
4378
4379         osd_trans_exec_check(env, th, OSD_OT_REF_ADD);
4380
4381         return rc;
4382 }
4383
4384 static int osd_declare_ref_del(const struct lu_env *env, struct dt_object *dt,
4385                                struct thandle *handle)
4386 {
4387         struct osd_thandle *oh;
4388
4389         if (!dt_object_exists(dt))
4390                 return -ENOENT;
4391
4392         LASSERT(!dt_object_remote(dt));
4393         LASSERT(handle != NULL);
4394
4395         oh = container_of(handle, struct osd_thandle, ot_super);
4396         LASSERT(oh->ot_handle == NULL);
4397
4398         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
4399                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4400
4401         return 0;
4402 }
4403
4404 /*
4405  * Concurrency: @dt is write locked.
4406  */
4407 static int osd_ref_del(const struct lu_env *env, struct dt_object *dt,
4408                        struct thandle *th)
4409 {
4410         struct osd_object *obj = osd_dt_obj(dt);
4411         struct inode *inode = obj->oo_inode;
4412         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4413         struct osd_thandle *oh;
4414
4415         if (!dt_object_exists(dt))
4416                 return -ENOENT;
4417
4418         LINVRNT(osd_invariant(obj));
4419         LASSERT(!dt_object_remote(dt));
4420         LASSERT(osd_is_write_locked(env, obj));
4421         LASSERT(th != NULL);
4422
4423         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_REF_DEL))
4424                 return -EIO;
4425
4426         oh = container_of(th, struct osd_thandle, ot_super);
4427         LASSERT(oh->ot_handle != NULL);
4428
4429         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
4430
4431         spin_lock(&obj->oo_guard);
4432         /*
4433          * That can be result of upgrade from old Lustre version and
4434          * applied only to local files.  Just skip this ref_del call.
4435          * ext4_unlink() only treats this as a warning, don't LASSERT here.
4436          */
4437         if (inode->i_nlink == 0) {
4438                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
4439                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
4440                              ", maybe an upgraded file? (LU-3915)\n",
4441                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
4442                 spin_unlock(&obj->oo_guard);
4443                 return 0;
4444         }
4445
4446         CDEBUG(D_INODE, DFID" decrease nlink %d\n",
4447                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4448
4449         osd_ldiskfs_dec_count(oh->ot_handle, inode);
4450         spin_unlock(&obj->oo_guard);
4451
4452         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4453         LINVRNT(osd_invariant(obj));
4454
4455         osd_trans_exec_check(env, th, OSD_OT_REF_DEL);
4456
4457         return 0;
4458 }
4459
4460 /*
4461  * Concurrency: @dt is read locked.
4462  */
4463 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
4464                          struct lu_buf *buf, const char *name)
4465 {
4466         struct osd_object      *obj    = osd_dt_obj(dt);
4467         struct inode           *inode  = obj->oo_inode;
4468         struct osd_thread_info *info   = osd_oti_get(env);
4469         struct dentry          *dentry = &info->oti_obj_dentry;
4470         bool cache_xattr = false;
4471         int rc;
4472
4473         LASSERT(buf);
4474
4475         /* version get is not real XATTR but uses xattr API */
4476         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4477                 dt_obj_version_t *ver = buf->lb_buf;
4478
4479                 /*
4480                  * for version we are just using xattr API but change inode
4481                  * field instead
4482                  */
4483                 if (buf->lb_len == 0)
4484                         return sizeof(dt_obj_version_t);
4485
4486                 if (buf->lb_len < sizeof(dt_obj_version_t))
4487                         return -ERANGE;
4488
4489                 CDEBUG(D_INODE, "Get version %#llx for inode %lu\n",
4490                        LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4491
4492                 *ver = LDISKFS_I(inode)->i_fs_version;
4493
4494                 return sizeof(dt_obj_version_t);
4495         }
4496
4497         if (!dt_object_exists(dt))
4498                 return -ENOENT;
4499
4500         LASSERT(!dt_object_remote(dt));
4501         LASSERT(inode->i_op != NULL);
4502 #ifdef HAVE_IOP_XATTR
4503         LASSERT(inode->i_op->getxattr != NULL);
4504 #endif
4505
4506         if (strcmp(name, XATTR_NAME_LOV) == 0 ||
4507             strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
4508                 cache_xattr = true;
4509
4510         if (cache_xattr) {
4511                 rc = osd_oxc_get(obj, name, buf);
4512                 if (rc != -ENOENT)
4513                         return rc;
4514         }
4515
4516         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4517                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4518                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4519                 struct filter_fid *ff;
4520                 struct ost_layout *ol;
4521
4522                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4523                 if (rc)
4524                         return rc;
4525
4526                 LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4527
4528                 rc = sizeof(*ff);
4529                 if (buf->lb_len == 0 || !buf->lb_buf)
4530                         return rc;
4531
4532                 if (buf->lb_len < rc)
4533                         return -ERANGE;
4534
4535                 ff = buf->lb_buf;
4536                 ol = &ff->ff_layout;
4537                 ol->ol_stripe_count = cpu_to_le32(loa->loa_parent_fid.f_ver >>
4538                                                   PFID_STRIPE_IDX_BITS);
4539                 ol->ol_stripe_size = cpu_to_le32(loa->loa_stripe_size);
4540                 loa->loa_parent_fid.f_ver &= PFID_STRIPE_COUNT_MASK;
4541                 fid_cpu_to_le(&ff->ff_parent, &loa->loa_parent_fid);
4542                 if (lma->lma_compat & LMAC_COMP_INFO) {
4543                         ol->ol_comp_start = cpu_to_le64(loa->loa_comp_start);
4544                         ol->ol_comp_end = cpu_to_le64(loa->loa_comp_end);
4545                         ol->ol_comp_id = cpu_to_le32(loa->loa_comp_id);
4546                 } else {
4547                         ol->ol_comp_start = 0;
4548                         ol->ol_comp_end = 0;
4549                         ol->ol_comp_id = 0;
4550                 }
4551         } else {
4552                 /* Get enc context xattr directly from ldiskfs instead of going
4553                  * through the VFS, as there is no xattr handler for
4554                  * "encryption.".
4555                  */
4556                 if (strcmp(name, LL_XATTR_NAME_ENCRYPTION_CONTEXT) == 0)
4557                         rc = ldiskfs_xattr_get(inode,
4558                                           LDISKFS_XATTR_INDEX_ENCRYPTION,
4559                                           LDISKFS_XATTR_NAME_ENCRYPTION_CONTEXT,
4560                                           buf->lb_buf, buf->lb_len);
4561                 else
4562                         rc = __osd_xattr_get(inode, dentry, name,
4563                                              buf->lb_buf, buf->lb_len);
4564         }
4565
4566         if (cache_xattr) {
4567                 if (rc == -ENOENT || rc == -ENODATA)
4568                         osd_oxc_add(obj, name, NULL, 0);
4569                 else if (rc > 0 && buf->lb_buf != NULL)
4570                         osd_oxc_add(obj, name, buf->lb_buf, rc);
4571         }
4572
4573         return rc;
4574 }
4575
4576 static int osd_declare_xattr_set(const struct lu_env *env,
4577                                  struct dt_object *dt,
4578                                  const struct lu_buf *buf, const char *name,
4579                                  int fl, struct thandle *handle)
4580 {
4581         struct osd_thandle *oh;
4582         int credits = 0;
4583         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4584
4585         LASSERT(handle != NULL);
4586
4587         oh = container_of(handle, struct osd_thandle, ot_super);
4588         LASSERT(oh->ot_handle == NULL);
4589
4590         if (strcmp(name, XATTR_NAME_LMA) == 0) {
4591                 /*
4592                  * For non-upgrading case, the LMA is set first and
4593                  * usually fit inode. But for upgrade case, the LMA
4594                  * may be in another separated EA block.
4595                  */
4596                 if (dt_object_exists(dt)) {
4597                         if (fl == LU_XATTR_REPLACE)
4598                                 credits = 1;
4599                         else
4600                                 goto upgrade;
4601                 }
4602         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4603                 credits = 1;
4604         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
4605                 /* We may need to delete the old PFID EA. */
4606                 credits = LDISKFS_MAXQUOTAS_DEL_BLOCKS(sb);
4607                 if (fl == LU_XATTR_REPLACE)
4608                         credits += 1;
4609                 else
4610                         goto upgrade;
4611         } else {
4612                 /*
4613                  * If some name entry resides on remote MDT, then will create
4614                  * agent entry under remote parent. On the other hand, if the
4615                  * remote entry will be removed, then related agent entry may
4616                  * need to be removed from the remote parent. So there may be
4617                  * kinds of cases, let's declare enough credits. The credits
4618                  * for create agent entry is enough for remove case.
4619                  */
4620                 if (strcmp(name, XATTR_NAME_LINK) == 0) {
4621                         credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
4622                         if (dt_object_exists(dt))
4623                                 credits += 1; /* For updating LMA */
4624                 }
4625
4626 upgrade:
4627                 credits += osd_dto_credits_noquota[DTO_XATTR_SET];
4628
4629                 if (buf != NULL) {
4630                         ssize_t buflen;
4631
4632                         if (buf->lb_buf == NULL && dt_object_exists(dt)) {
4633                                 /*
4634                                  * learn xattr size from osd_xattr_get if
4635                                  * attribute has not been read yet
4636                                  */
4637                                 buflen = __osd_xattr_get(
4638                                     osd_dt_obj(dt)->oo_inode,
4639                                     &osd_oti_get(env)->oti_obj_dentry,
4640                                     name, NULL, 0);
4641                                 if (buflen < 0)
4642                                         buflen = 0;
4643                         } else {
4644                                 buflen = buf->lb_len;
4645                         }
4646
4647                         if (buflen > sb->s_blocksize) {
4648                                 credits += osd_calc_bkmap_credits(
4649                                     sb, NULL, 0, -1,
4650                                     (buflen + sb->s_blocksize - 1) >>
4651                                     sb->s_blocksize_bits);
4652                         }
4653                 }
4654                 /*
4655                  * xattr set may involve inode quota change, reserve credits for
4656                  * dquot_initialize()
4657                  */
4658                 credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4659         }
4660
4661         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
4662
4663         return 0;
4664 }
4665
4666 static int osd_xattr_set_pfid(const struct lu_env *env, struct osd_object *obj,
4667                               const struct lu_buf *buf, int fl,
4668                               struct thandle *handle)
4669 {
4670         struct osd_thread_info *info = osd_oti_get(env);
4671         struct dentry *dentry = &info->oti_obj_dentry;
4672         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4673         struct lustre_mdt_attrs *lma = &loa->loa_lma;
4674         struct inode *inode = obj->oo_inode;
4675         struct filter_fid *ff = buf->lb_buf;
4676         struct ost_layout *ol = &ff->ff_layout;
4677         int flags = XATTR_REPLACE;
4678         int rc;
4679
4680         ENTRY;
4681
4682         if (buf->lb_len != sizeof(*ff) && buf->lb_len != sizeof(struct lu_fid))
4683                 RETURN(-EINVAL);
4684
4685         rc = osd_get_lma(info, inode, dentry, loa);
4686         if (rc == -ENODATA) {
4687                 /* Usually for upgarding from old device */
4688                 lustre_loa_init(loa, lu_object_fid(&obj->oo_dt.do_lu),
4689                                 LMAC_FID_ON_OST, 0);
4690                 flags = XATTR_CREATE;
4691         } else if (rc) {
4692                 RETURN(rc);
4693         }
4694
4695         if (!rc && lma->lma_compat & LMAC_STRIPE_INFO) {
4696                 if ((fl & LU_XATTR_CREATE) && !(fl & LU_XATTR_REPLACE))
4697                         RETURN(-EEXIST);
4698
4699                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256) {
4700                         /* Separate PFID EA from LMA */
4701                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4702                         lustre_lma_swab(lma);
4703                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4704                                              sizeof(*lma), XATTR_REPLACE);
4705                         if (!rc) {
4706                                 obj->oo_pfid_in_lma = 0;
4707                                 rc = LU_XATTR_CREATE;
4708                         }
4709
4710                         RETURN(rc);
4711                 }
4712         } else {
4713                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256)
4714                         RETURN(fl);
4715
4716                 /*
4717                  * Old client does not send stripe information,
4718                  * then store the PFID EA on disk separatedly.
4719                  */
4720                 if (unlikely(buf->lb_len == sizeof(struct lu_fid) ||
4721                              ol->ol_stripe_size == 0))
4722                         RETURN(fl);
4723
4724                 /* Remove old PFID EA entry firstly. */
4725                 dquot_initialize(inode);
4726                 rc = ll_vfs_removexattr(dentry, inode, XATTR_NAME_FID);
4727                 if (rc == -ENODATA) {
4728                         /* XATTR_NAME_FID is already absent */
4729                         rc = 0;
4730                 } else if (rc) {
4731                         RETURN(rc);
4732                 }
4733         }
4734
4735         fid_le_to_cpu(&loa->loa_parent_fid, &ff->ff_parent);
4736         if (likely(ol->ol_stripe_size != 0)) {
4737                 loa->loa_parent_fid.f_ver |= le32_to_cpu(ol->ol_stripe_count) <<
4738                                              PFID_STRIPE_IDX_BITS;
4739                 loa->loa_stripe_size = le32_to_cpu(ol->ol_stripe_size);
4740                 lma->lma_compat |= LMAC_STRIPE_INFO;
4741                 if (ol->ol_comp_id != 0) {
4742                         loa->loa_comp_id = le32_to_cpu(ol->ol_comp_id);
4743                         loa->loa_comp_start = le64_to_cpu(ol->ol_comp_start);
4744                         loa->loa_comp_end = le64_to_cpu(ol->ol_comp_end);
4745                         lma->lma_compat |= LMAC_COMP_INFO;
4746                 }
4747         }
4748
4749         lustre_loa_swab(loa, false);
4750
4751         /* Store the PFID EA inside LMA. */
4752         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa, sizeof(*loa),
4753                              flags);
4754         if (!rc)
4755                 obj->oo_pfid_in_lma = 1;
4756
4757         RETURN(rc);
4758 }
4759
4760 /*
4761  * In DNE environment, the object (in spite of regular file or directory)
4762  * and its name entry may reside on different MDTs. Under such case, we will
4763  * create an agent entry on the MDT where the object resides. The agent entry
4764  * references the object locally, that makes the object to be visible to the
4765  * userspace when mounted as 'ldiskfs' directly. Then the userspace tools,
4766  * such as 'tar' can handle the object properly.
4767  *
4768  * We handle the agent entry during set linkEA that is the common interface
4769  * for both regular file and directroy, can handle kinds of cases, such as
4770  * create/link/unlink/rename, and so on.
4771  *
4772  * NOTE: we can NOT do that when ea_{insert,delete} that is only for directory.
4773  *
4774  * XXX: There are two known issues:
4775  * 1. For one object, we will create at most one agent entry even if there
4776  *    may be more than one cross-MDTs hard links on the object. So the local
4777  *    e2fsck may claim that the object's nlink is larger than the name entries
4778  *    that reference such inode. And in further, the e2fsck will fix the nlink
4779  *    attribute to match the local references. Then it will cause the object's
4780  *    nlink attribute to be inconsistent with the global references. it is bad
4781  *    but not fatal. The ref_del() can handle the zero-referenced case. On the
4782  *    other hand, the global namespace LFSCK can repair the object's attribute
4783  *    according to the linkEA.
4784  * 2. There may be too many hard links on the object as to its linkEA overflow,
4785  *    then the linkEA entry for cross-MDTs reference may be discarded. If such
4786  *    case happened, then at this point, we do not know whether there are some
4787  *    cross-MDTs reference. But there are local references, it guarantees that
4788  *    object is visible to userspace when mounted as 'ldiskfs'. That is enough.
4789  */
4790 static int osd_xattr_handle_linkea(const struct lu_env *env,
4791                                    struct osd_device *osd,
4792                                    struct osd_object *obj,
4793                                    const struct lu_buf *buf,
4794                                    struct thandle *handle)
4795 {
4796         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
4797         struct lu_fid *tfid = &osd_oti_get(env)->oti_fid3;
4798         struct linkea_data ldata = { .ld_buf = (struct lu_buf *)buf };
4799         struct lu_name tmpname;
4800         struct osd_thandle *oh;
4801         int rc;
4802         bool remote = false;
4803
4804         ENTRY;
4805
4806         oh = container_of(handle, struct osd_thandle, ot_super);
4807         LASSERT(oh->ot_handle != NULL);
4808
4809         rc = linkea_init_with_rec(&ldata);
4810         if (!rc) {
4811                 linkea_first_entry(&ldata);
4812                 while (ldata.ld_lee != NULL && !remote) {
4813                         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen,
4814                                             &tmpname, tfid);
4815                         if (osd_remote_fid(env, osd, tfid) > 0)
4816                                 remote = true;
4817                         else
4818                                 linkea_next_entry(&ldata);
4819                 }
4820         } else if (rc == -ENODATA) {
4821                 rc = 0;
4822         } else {
4823                 RETURN(rc);
4824         }
4825
4826         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu) && !remote) {
4827                 rc = osd_delete_from_remote_parent(env, osd, obj, oh, false);
4828                 if (rc)
4829                         CERROR("%s: failed to remove agent entry for "DFID
4830                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4831         } else if (!lu_object_has_agent_entry(&obj->oo_dt.do_lu) && remote) {
4832                 rc = osd_add_to_remote_parent(env, osd, obj, oh);
4833                 if (rc)
4834                         CERROR("%s: failed to create agent entry for "DFID
4835                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4836         }
4837
4838         RETURN(rc);
4839 }
4840
4841 /*
4842  * Concurrency: @dt is write locked.
4843  */
4844 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
4845                          const struct lu_buf *buf, const char *name, int fl,
4846                          struct thandle *handle)
4847 {
4848         struct osd_object *obj = osd_dt_obj(dt);
4849         struct osd_device *osd = osd_obj2dev(obj);
4850         struct inode *inode = obj->oo_inode;
4851         struct osd_thread_info *info = osd_oti_get(env);
4852         int fs_flags = 0;
4853         int len;
4854         int rc;
4855
4856         ENTRY;
4857
4858         LASSERT(handle);
4859         LASSERT(buf);
4860
4861         /* version set is not real XATTR */
4862         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4863                 dt_obj_version_t *version = buf->lb_buf;
4864
4865                 /*
4866                  * for version we are just using xattr API but change inode
4867                  * field instead
4868                  */
4869                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
4870
4871                 CDEBUG(D_INODE, "Set version %#llx (old %#llx) for inode %lu\n",
4872                        *version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4873
4874                 LDISKFS_I(inode)->i_fs_version = *version;
4875                 /*
4876                  * Version is set after all inode operations are finished,
4877                  * so we should mark it dirty here
4878                  */
4879                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4880
4881                 RETURN(0);
4882         }
4883
4884         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zu\n",
4885                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
4886
4887         len = buf->lb_len;
4888         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4889
4890         /*
4891          * For the OST device with 256 bytes inode size by default,
4892          * the PFID EA will be stored together with LMA EA to avoid
4893          * performance trouble. Otherwise the PFID EA can be stored
4894          * independently. LU-8998
4895          */
4896         if (strcmp(name, XATTR_NAME_FID) == 0 && osd->od_is_ost &&
4897             (LDISKFS_INODE_SIZE(inode->i_sb) <= 256 || obj->oo_pfid_in_lma)) {
4898                 LASSERT(buf->lb_buf);
4899
4900                 fl = osd_xattr_set_pfid(env, obj, buf, fl, handle);
4901                 if (fl <= 0)
4902                         RETURN(fl);
4903         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
4904                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4905                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4906
4907                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4908                 if (rc)
4909                         RETURN(rc);
4910
4911                 lma->lma_incompat |= LMAI_STRIPED;
4912                 lustre_lma_swab(lma);
4913                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4914                                      sizeof(*lma), XATTR_REPLACE);
4915                 if (rc != 0)
4916                         RETURN(rc);
4917         } else if (strcmp(name, XATTR_NAME_LINK) == 0) {
4918                 LASSERT(!osd->od_is_ost);
4919
4920                 rc = osd_xattr_handle_linkea(env, osd, obj, buf, handle);
4921                 if (rc)
4922                         RETURN(rc);
4923         }
4924
4925         if (fl & LU_XATTR_REPLACE)
4926                 fs_flags |= XATTR_REPLACE;
4927
4928         if (fl & LU_XATTR_CREATE)
4929                 fs_flags |= XATTR_CREATE;
4930
4931         if (strcmp(name, LL_XATTR_NAME_ENCRYPTION_CONTEXT) == 0) {
4932                 /* Set enc context xattr directly in ldiskfs instead of going
4933                  * through the VFS, as there is no xattr handler for
4934                  * "encryption.".
4935                  */
4936                 struct osd_thandle *oth = container_of(handle,
4937                                                        struct osd_thandle,
4938                                                        ot_super);
4939
4940                 if (!oth->ot_handle)
4941                         /* this should be already part of a transaction */
4942                         RETURN(-EPROTO);
4943
4944                 rc = ldiskfs_xattr_set_handle(oth->ot_handle, inode,
4945                                           LDISKFS_XATTR_INDEX_ENCRYPTION,
4946                                           LDISKFS_XATTR_NAME_ENCRYPTION_CONTEXT,
4947                                           buf->lb_buf, len, fs_flags);
4948         } else {
4949                 rc = __osd_xattr_set(info, inode, name,
4950                                      buf->lb_buf, len, fs_flags);
4951         }
4952         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4953
4954         if (rc == 0 &&
4955             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4956              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4957                 osd_oxc_add(obj, name, buf->lb_buf, buf->lb_len);
4958
4959         return rc;
4960 }
4961
4962 /*
4963  * Concurrency: @dt is read locked.
4964  */
4965 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
4966                           const struct lu_buf *buf)
4967 {
4968         struct osd_object *obj = osd_dt_obj(dt);
4969         struct osd_device *dev = osd_obj2dev(obj);
4970         struct inode *inode = obj->oo_inode;
4971         struct osd_thread_info *info = osd_oti_get(env);
4972         struct dentry *dentry = &info->oti_obj_dentry;
4973         int rc;
4974
4975         if (!dt_object_exists(dt))
4976                 return -ENOENT;
4977
4978         LASSERT(!dt_object_remote(dt));
4979         LASSERT(inode->i_op != NULL);
4980         LASSERT(inode->i_op->listxattr != NULL);
4981
4982         dentry->d_inode = inode;
4983         dentry->d_sb = inode->i_sb;
4984         rc = inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
4985
4986         if (rc < 0 || buf->lb_buf == NULL)
4987                 return rc;
4988
4989         /* Hide virtual project ID xattr from list if disabled */
4990         if (!dev->od_enable_projid_xattr) {
4991                 char *end = (char *)buf->lb_buf + rc;
4992                 char *p = buf->lb_buf;
4993
4994                 while (p < end) {
4995                         char *next = p + strlen(p) + 1;
4996
4997                         if (strcmp(p, XATTR_NAME_PROJID) == 0) {
4998                                 if (end - next > 0)
4999                                         memmove(p, next, end - next);
5000                                 rc -= next - p;
5001                                 break;
5002                         }
5003
5004                         p = next;
5005                 }
5006         }
5007
5008         return rc;
5009 }
5010
5011 static int osd_declare_xattr_del(const struct lu_env *env,
5012                                  struct dt_object *dt, const char *name,
5013                                  struct thandle *handle)
5014 {
5015         struct osd_thandle *oh;
5016         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
5017
5018         LASSERT(!dt_object_remote(dt));
5019         LASSERT(handle != NULL);
5020
5021         oh = container_of(handle, struct osd_thandle, ot_super);
5022         LASSERT(oh->ot_handle == NULL);
5023
5024         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
5025                              osd_dto_credits_noquota[DTO_XATTR_SET]);
5026         /*
5027          * xattr del may involve inode quota change, reserve credits for
5028          * dquot_initialize()
5029          */
5030         oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
5031
5032         return 0;
5033 }
5034
5035 /*
5036  * Concurrency: @dt is write locked.
5037  */
5038 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
5039                          const char *name, struct thandle *handle)
5040 {
5041         struct osd_object *obj = osd_dt_obj(dt);
5042         struct inode *inode = obj->oo_inode;
5043         struct osd_thread_info *info = osd_oti_get(env);
5044         struct dentry *dentry = &info->oti_obj_dentry;
5045         int rc;
5046
5047         if (!dt_object_exists(dt))
5048                 return -ENOENT;
5049
5050         LASSERT(!dt_object_remote(dt));
5051         LASSERT(inode->i_op != NULL);
5052         LASSERT(handle != NULL);
5053 #ifdef HAVE_IOP_XATTR
5054         LASSERT(inode->i_op->removexattr != NULL);
5055 #endif
5056
5057         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
5058
5059         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
5060                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
5061
5062                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
5063                                  &info->oti_ost_attrs);
5064                 if (!rc) {
5065                         LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
5066
5067                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
5068                         lustre_lma_swab(lma);
5069                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
5070                                              sizeof(*lma), XATTR_REPLACE);
5071                         if (!rc)
5072                                 obj->oo_pfid_in_lma = 0;
5073                 }
5074         } else {
5075                 dquot_initialize(inode);
5076                 dentry->d_inode = inode;
5077                 dentry->d_sb = inode->i_sb;
5078                 rc = ll_vfs_removexattr(dentry, inode, name);
5079         }
5080
5081         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
5082
5083         if (rc == 0 &&
5084             (strcmp(name, XATTR_NAME_LOV) == 0 ||
5085              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
5086                 osd_oxc_del(obj, name);
5087
5088         return rc;
5089 }
5090
5091 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt,
5092                            __u64 start, __u64 end)
5093 {
5094         struct osd_object *obj = osd_dt_obj(dt);
5095         struct osd_device *dev = osd_obj2dev(obj);
5096         struct inode *inode = obj->oo_inode;
5097         struct file *file;
5098         int rc;
5099
5100         ENTRY;
5101         file = alloc_file_pseudo(inode, dev->od_mnt, "/", O_NOATIME,
5102                                  inode->i_fop);
5103         if (IS_ERR(file))
5104                 RETURN(PTR_ERR(file));
5105
5106         file->f_mode |= FMODE_64BITHASH;
5107         rc = vfs_fsync_range(file, start, end, 0);
5108         ihold(inode);
5109         fput(file);
5110
5111         RETURN(rc);
5112 }
5113
5114 static int osd_invalidate(const struct lu_env *env, struct dt_object *dt)
5115 {
5116         return 0;
5117 }
5118
5119 static bool osd_check_stale(struct dt_object *dt)
5120 {
5121         return false;
5122 }
5123 /*
5124  * Index operations.
5125  */
5126
5127 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
5128                                const struct dt_index_features *feat)
5129 {
5130         struct iam_descr *descr;
5131
5132         if (osd_object_is_root(o))
5133                 return feat == &dt_directory_features;
5134
5135         LASSERT(o->oo_dir != NULL);
5136
5137         descr = o->oo_dir->od_container.ic_descr;
5138         if (feat == &dt_directory_features) {
5139                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
5140                         return 1;
5141                 else
5142                         return 0;
5143         } else {
5144                 return feat->dif_keysize_min <= descr->id_key_size &&
5145                        descr->id_key_size <= feat->dif_keysize_max &&
5146                        feat->dif_recsize_min <= descr->id_rec_size &&
5147                        descr->id_rec_size <= feat->dif_recsize_max &&
5148                        !(feat->dif_flags & (DT_IND_VARKEY |
5149                                             DT_IND_VARREC | DT_IND_NONUNQ)) &&
5150                        ergo(feat->dif_flags & DT_IND_UPDATE,
5151                             1 /* XXX check that object (and fs) is writable */);
5152         }
5153 }
5154
5155 static int osd_iam_container_init(const struct lu_env *env,
5156                                   struct osd_object *obj,
5157                                   struct osd_directory *dir)
5158 {
5159         struct iam_container *bag = &dir->od_container;
5160         int result;
5161
5162         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
5163         if (result != 0)
5164                 return result;
5165
5166         result = iam_container_setup(bag);
5167         if (result == 0)
5168                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
5169         else
5170                 iam_container_fini(bag);
5171
5172         return result;
5173 }
5174
5175
5176 /*
5177  * Concurrency: no external locking is necessary.
5178  */
5179 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
5180                          const struct dt_index_features *feat)
5181 {
5182         int result;
5183         int skip_iam = 0;
5184         struct osd_object *obj = osd_dt_obj(dt);
5185
5186         LINVRNT(osd_invariant(obj));
5187
5188         if (osd_object_is_root(obj)) {
5189                 dt->do_index_ops = &osd_index_ea_ops;
5190                 result = 0;
5191         } else if (feat == &dt_directory_features) {
5192                 dt->do_index_ops = &osd_index_ea_ops;
5193                 if (obj->oo_inode == NULL || S_ISDIR(obj->oo_inode->i_mode))
5194                         result = 0;
5195                 else
5196                         result = -ENOTDIR;
5197                 skip_iam = 1;
5198         } else if (unlikely(feat == &dt_otable_features)) {
5199                 dt->do_index_ops = &osd_otable_ops;
5200                 return 0;
5201         } else if (unlikely(feat == &dt_acct_features)) {
5202                 dt->do_index_ops = &osd_acct_index_ops;
5203                 result = 0;
5204                 skip_iam = 1;
5205         } else if (!osd_has_index(obj)) {
5206                 struct osd_directory *dir;
5207                 struct osd_device *osd = osd_obj2dev(obj);
5208                 const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
5209
5210                 OBD_ALLOC_PTR(dir);
5211                 if (dir) {
5212
5213                         spin_lock(&obj->oo_guard);
5214                         if (obj->oo_dir == NULL)
5215                                 obj->oo_dir = dir;
5216                         else
5217                                 /*
5218                                  * Concurrent thread allocated container data.
5219                                  */
5220                                 OBD_FREE_PTR(dir);
5221                         spin_unlock(&obj->oo_guard);
5222                         /*
5223                          * Now, that we have container data, serialize its
5224                          * initialization.
5225                          */
5226                         down_write(&obj->oo_ext_idx_sem);
5227                         /*
5228                          * recheck under lock.
5229                          */
5230
5231                         if (osd_has_index(obj)) {
5232                                 result = 0;
5233                                 goto unlock;
5234                         }
5235
5236                         result = osd_iam_container_init(env, obj, obj->oo_dir);
5237                         if (result || feat == &dt_lfsck_namespace_features ||
5238                             feat == &dt_lfsck_layout_orphan_features ||
5239                             feat == &dt_lfsck_layout_dangling_features)
5240                                 goto unlock;
5241
5242                         result = osd_index_register(osd, fid,
5243                                                     feat->dif_keysize_max,
5244                                                     feat->dif_recsize_max);
5245                         if (result < 0)
5246                                 CWARN("%s: failed to register index "
5247                                       DFID": rc = %d\n",
5248                                       osd_name(osd), PFID(fid), result);
5249                         else if (result > 0)
5250                                 result = 0;
5251                         else
5252                                 CDEBUG(D_LFSCK, "%s: index object "DFID
5253                                        " (%d/%d) registered\n",
5254                                        osd_name(osd), PFID(fid),
5255                                        (int)feat->dif_keysize_max,
5256                                        (int)feat->dif_recsize_max);
5257
5258 unlock:
5259                         up_write(&obj->oo_ext_idx_sem);
5260                 } else {
5261                         result = -ENOMEM;
5262                 }
5263         } else {
5264                 result = 0;
5265         }
5266
5267         if (result == 0 && skip_iam == 0) {
5268                 if (!osd_iam_index_probe(env, obj, feat))
5269                         result = -ENOTDIR;
5270         }
5271         LINVRNT(osd_invariant(obj));
5272
5273         return result;
5274 }
5275
5276 static int osd_otable_it_attr_get(const struct lu_env *env,
5277                                  struct dt_object *dt,
5278                                  struct lu_attr *attr)
5279 {
5280         attr->la_valid = 0;
5281         return 0;
5282 }
5283
5284 static const struct dt_object_operations osd_obj_ops = {
5285         .do_read_lock           = osd_read_lock,
5286         .do_write_lock          = osd_write_lock,
5287         .do_read_unlock         = osd_read_unlock,
5288         .do_write_unlock        = osd_write_unlock,
5289         .do_write_locked        = osd_write_locked,
5290         .do_attr_get            = osd_attr_get,
5291         .do_declare_attr_set    = osd_declare_attr_set,
5292         .do_attr_set            = osd_attr_set,
5293         .do_ah_init             = osd_ah_init,
5294         .do_declare_create      = osd_declare_create,
5295         .do_create              = osd_create,
5296         .do_declare_destroy     = osd_declare_destroy,
5297         .do_destroy             = osd_destroy,
5298         .do_index_try           = osd_index_try,
5299         .do_declare_ref_add     = osd_declare_ref_add,
5300         .do_ref_add             = osd_ref_add,
5301         .do_declare_ref_del     = osd_declare_ref_del,
5302         .do_ref_del             = osd_ref_del,
5303         .do_xattr_get           = osd_xattr_get,
5304         .do_declare_xattr_set   = osd_declare_xattr_set,
5305         .do_xattr_set           = osd_xattr_set,
5306         .do_declare_xattr_del   = osd_declare_xattr_del,
5307         .do_xattr_del           = osd_xattr_del,
5308         .do_xattr_list          = osd_xattr_list,
5309         .do_object_sync         = osd_object_sync,
5310         .do_invalidate          = osd_invalidate,
5311         .do_check_stale         = osd_check_stale,
5312 };
5313
5314 static const struct dt_object_operations osd_obj_otable_it_ops = {
5315         .do_attr_get    = osd_otable_it_attr_get,
5316         .do_index_try   = osd_index_try,
5317 };
5318
5319 static int osd_index_declare_iam_delete(const struct lu_env *env,
5320                                         struct dt_object *dt,
5321                                         const struct dt_key *key,
5322                                         struct thandle *handle)
5323 {
5324         struct osd_thandle *oh;
5325
5326         oh = container_of(handle, struct osd_thandle, ot_super);
5327         LASSERT(oh->ot_handle == NULL);
5328
5329         /* Recycle  may cause additional three blocks to be changed. */
5330         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
5331                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
5332
5333         return 0;
5334 }
5335
5336 /**
5337  *      delete a (key, value) pair from index \a dt specified by \a key
5338  *
5339  *      \param  dt      osd index object
5340  *      \param  key     key for index
5341  *      \param  rec     record reference
5342  *      \param  handle  transaction handler
5343  *
5344  *      \retval  0  success
5345  *      \retval -ve   failure
5346  */
5347 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
5348                                 const struct dt_key *key,
5349                                 struct thandle *handle)
5350 {
5351         struct osd_thread_info *oti = osd_oti_get(env);
5352         struct osd_object *obj = osd_dt_obj(dt);
5353         struct osd_thandle *oh;
5354         struct iam_path_descr *ipd;
5355         struct iam_container *bag = &obj->oo_dir->od_container;
5356         int rc;
5357
5358         ENTRY;
5359
5360         if (!dt_object_exists(dt))
5361                 RETURN(-ENOENT);
5362
5363         LINVRNT(osd_invariant(obj));
5364         LASSERT(!dt_object_remote(dt));
5365         LASSERT(bag->ic_object == obj->oo_inode);
5366         LASSERT(handle != NULL);
5367
5368         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5369
5370         ipd = osd_idx_ipd_get(env, bag);
5371         if (unlikely(ipd == NULL))
5372                 RETURN(-ENOMEM);
5373
5374         oh = container_of(handle, struct osd_thandle, ot_super);
5375         LASSERT(oh->ot_handle != NULL);
5376         LASSERT(oh->ot_handle->h_transaction != NULL);
5377
5378         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5379                 /* swab quota uid/gid provided by caller */
5380                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5381                 key = (const struct dt_key *)&oti->oti_quota_id;
5382         }
5383
5384         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
5385         osd_ipd_put(env, bag, ipd);
5386         LINVRNT(osd_invariant(obj));
5387         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5388         RETURN(rc);
5389 }
5390
5391 static int osd_index_declare_ea_delete(const struct lu_env *env,
5392                                        struct dt_object *dt,
5393                                        const struct dt_key *key,
5394                                        struct thandle *handle)
5395 {
5396         struct osd_thandle *oh;
5397         struct inode *inode;
5398         int rc, credits;
5399
5400         ENTRY;
5401
5402         LASSERT(!dt_object_remote(dt));
5403         LASSERT(handle != NULL);
5404
5405         oh = container_of(handle, struct osd_thandle, ot_super);
5406         LASSERT(oh->ot_handle == NULL);
5407
5408         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE];
5409         osd_trans_declare_op(env, oh, OSD_OT_DELETE, credits);
5410
5411         inode = osd_dt_obj(dt)->oo_inode;
5412         if (inode == NULL)
5413                 RETURN(-ENOENT);
5414
5415         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
5416                                    i_projid_read(inode), 0, oh, osd_dt_obj(dt),
5417                                    NULL, OSD_QID_BLK);
5418         RETURN(rc);
5419 }
5420
5421 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
5422                                           struct dt_rec *fid)
5423 {
5424         struct osd_fid_pack *rec;
5425         int rc = -ENODATA;
5426
5427         if (de->file_type & LDISKFS_DIRENT_LUFID) {
5428                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
5429                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
5430                 if (rc == 0 && unlikely(!fid_is_sane((struct lu_fid *)fid)))
5431                         rc = -EINVAL;
5432         }
5433         return rc;
5434 }
5435
5436 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
5437                           const struct lu_fid *fid)
5438 {
5439         struct seq_server_site *ss = osd_seq_site(osd);
5440
5441         ENTRY;
5442
5443         /* FID seqs not in FLDB, must be local seq */
5444         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
5445                 RETURN(0);
5446
5447         /*
5448          * If FLD is not being initialized yet, it only happens during the
5449          * initialization, likely during mgs initialization, and we assume
5450          * this is local FID.
5451          */
5452         if (ss == NULL || ss->ss_server_fld == NULL)
5453                 RETURN(0);
5454
5455         /* Only check the local FLDB here */
5456         if (osd_seq_exists(env, osd, fid_seq(fid)))
5457                 RETURN(0);
5458
5459         RETURN(1);
5460 }
5461
5462 static void osd_take_care_of_agent(const struct lu_env *env,
5463                                    struct osd_device *osd,
5464                                    struct osd_thandle *oh,
5465                                    struct ldiskfs_dir_entry_2 *de)
5466 {
5467         struct lu_fid *fid = &osd_oti_get(env)->oti_fid;
5468         struct osd_idmap_cache *idc;
5469         int rc, schedule = 0;
5470
5471         LASSERT(de != NULL);
5472
5473         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
5474         if (likely(rc == 0)) {
5475                 idc = osd_idc_find_or_init(env, osd, fid);
5476                 if (IS_ERR(idc) || idc->oic_remote)
5477                         schedule = 1;
5478         } else if (rc == -ENODATA) {
5479                 /*
5480                  * can't get FID, postpone to the end of the
5481                  * transaction when iget() is safe
5482                  */
5483                 schedule = 1;
5484         } else {
5485                 CERROR("%s: can't get FID: rc = %d\n", osd_name(osd), rc);
5486         }
5487         if (schedule)
5488                 osd_schedule_agent_inode_removal(env, oh,
5489                                                  le32_to_cpu(de->inode));
5490 }
5491
5492 /**
5493  * Utility function to get real name from object name
5494  *
5495  * \param[in] obj      pointer to the object to be handled
5496  * \param[in] name     object name
5497  * \param[in] len      object name len
5498  * \param[out]ln       pointer to the struct lu_name to hold the real name
5499  *
5500  * If file is not encrypted, real name is just the object name.
5501  * If file is encrypted, object name needs to be decoded. In
5502  * this case a new buffer is allocated, and ln->ln_name needs to be freed by
5503  * the caller.
5504  *
5505  * \retval   0, on success
5506  * \retval -ve, on error
5507  */
5508 static int obj_name2lu_name(struct osd_object *obj, const char *name,
5509                             int len, struct lu_name *ln)
5510 {
5511         if (!(obj->oo_lma_flags & LUSTRE_ENCRYPT_FL)) {
5512                 ln->ln_name = name;
5513                 ln->ln_namelen = len;
5514         } else {
5515                 char *buf = kmalloc(len, GFP_NOFS);
5516
5517                 if (!buf)
5518                         return -ENOMEM;
5519
5520                 len = critical_decode(name, len, buf);
5521                 ln->ln_name = buf;
5522                 ln->ln_namelen = len;
5523         }
5524
5525         return 0;
5526 }
5527
5528 /**
5529  * Index delete function for interoperability mode (b11826).
5530  * It will remove the directory entry added by osd_index_ea_insert().
5531  * This entry is needed to maintain name->fid mapping.
5532  *
5533  * \param key,  key i.e. file entry to be deleted
5534  *
5535  * \retval   0, on success
5536  * \retval -ve, on error
5537  */
5538 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
5539                                const struct dt_key *key, struct thandle *handle)
5540 {
5541         struct osd_object *obj = osd_dt_obj(dt);
5542         struct inode *dir = obj->oo_inode;
5543         struct dentry *dentry;
5544         struct osd_thandle *oh;
5545         struct ldiskfs_dir_entry_2 *de = NULL;
5546         struct buffer_head *bh;
5547         struct htree_lock *hlock = NULL;
5548         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
5549         struct lu_name ln;
5550         int rc;
5551
5552         ENTRY;
5553
5554         if (!dt_object_exists(dt))
5555                 RETURN(-ENOENT);
5556
5557         LINVRNT(osd_invariant(obj));
5558         LASSERT(!dt_object_remote(dt));
5559         LASSERT(handle != NULL);
5560
5561         rc = obj_name2lu_name(obj, (char *)key, strlen((char *)key), &ln);
5562         if (rc)
5563                 RETURN(rc);
5564
5565         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5566
5567         oh = container_of(handle, struct osd_thandle, ot_super);
5568         LASSERT(oh->ot_handle != NULL);
5569         LASSERT(oh->ot_handle->h_transaction != NULL);
5570
5571         dquot_initialize(dir);
5572         dentry = osd_child_dentry_get(env, obj, ln.ln_name, ln.ln_namelen);
5573
5574         if (obj->oo_hl_head != NULL) {
5575                 hlock = osd_oti_get(env)->oti_hlock;
5576                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5577                                    dir, LDISKFS_HLOCK_DEL);
5578         } else {
5579                 down_write(&obj->oo_ext_idx_sem);
5580         }
5581
5582         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5583         if (!IS_ERR(bh)) {
5584                 /*
5585                  * If this is not the ".." entry, it might be a remote DNE
5586                  * entry and  we need to check if the FID is for a remote
5587                  * MDT.  If the FID is  not in the directory entry (e.g.
5588                  * upgraded 1.8 filesystem without dirdata enabled) then
5589                  * we need to get the FID from the LMA. For a remote directory
5590                  * there HAS to be an LMA, it cannot be an IGIF inode in this
5591                  * case.
5592                  *
5593                  * Delete the entry before the agent inode in order to
5594                  * simplify error handling.  At worst an error after deleting
5595                  * the entry first might leak the agent inode afterward. The
5596                  * reverse would need filesystem abort in case of error deleting
5597                  * the entry after the agent had been removed, or leave a
5598                  * dangling entry pointing at a random inode.
5599                  */
5600                 if (strcmp((char *)key, dotdot) != 0)
5601                         osd_take_care_of_agent(env, osd, oh, de);
5602                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
5603                 brelse(bh);
5604         } else {
5605                 rc = PTR_ERR(bh);
5606         }
5607
5608         if (!rc && fid_is_namespace_visible(lu_object_fid(&dt->do_lu)) &&
5609             obj->oo_dirent_count != LU_DIRENT_COUNT_UNSET) {
5610                 /* NB, dirent count may not be accurate, because it's counted
5611                  * without lock.
5612                  */
5613                 if (obj->oo_dirent_count)
5614                         obj->oo_dirent_count--;
5615                 else
5616                         obj->oo_dirent_count = LU_DIRENT_COUNT_UNSET;
5617         }
5618         if (hlock != NULL)
5619                 ldiskfs_htree_unlock(hlock);
5620         else
5621                 up_write(&obj->oo_ext_idx_sem);
5622         GOTO(out, rc);
5623 out:
5624         LASSERT(osd_invariant(obj));
5625         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5626         if (ln.ln_name != (char *)key)
5627                 kfree(ln.ln_name);
5628         RETURN(rc);
5629 }
5630
5631 /**
5632  *      Lookup index for \a key and copy record to \a rec.
5633  *
5634  *      \param  dt      osd index object
5635  *      \param  key     key for index
5636  *      \param  rec     record reference
5637  *
5638  *      \retval  +ve  success : exact mach
5639  *      \retval  0    return record with key not greater than \a key
5640  *      \retval -ve   failure
5641  */
5642 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
5643                                 struct dt_rec *rec, const struct dt_key *key)
5644 {
5645         struct osd_object *obj = osd_dt_obj(dt);
5646         struct iam_path_descr *ipd;
5647         struct iam_container *bag = &obj->oo_dir->od_container;
5648         struct osd_thread_info *oti = osd_oti_get(env);
5649         struct iam_iterator *it = &oti->oti_idx_it;
5650         struct iam_rec *iam_rec;
5651         int rc;
5652
5653         ENTRY;
5654
5655         if (!dt_object_exists(dt))
5656                 RETURN(-ENOENT);
5657
5658         LASSERT(osd_invariant(obj));
5659         LASSERT(!dt_object_remote(dt));
5660         LASSERT(bag->ic_object == obj->oo_inode);
5661
5662         ipd = osd_idx_ipd_get(env, bag);
5663         if (IS_ERR(ipd))
5664                 RETURN(-ENOMEM);
5665
5666         /* got ipd now we can start iterator. */
5667         iam_it_init(it, bag, 0, ipd);
5668
5669         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5670                 /* swab quota uid/gid provided by caller */
5671                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5672                 key = (const struct dt_key *)&oti->oti_quota_id;
5673         }
5674
5675         rc = iam_it_get(it, (struct iam_key *)key);
5676         if (rc >= 0) {
5677                 if (S_ISDIR(obj->oo_inode->i_mode))
5678                         iam_rec = (struct iam_rec *)oti->oti_ldp;
5679                 else
5680                         iam_rec = (struct iam_rec *)rec;
5681
5682                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
5683
5684                 if (S_ISDIR(obj->oo_inode->i_mode))
5685                         osd_fid_unpack((struct lu_fid *)rec,
5686                                        (struct osd_fid_pack *)iam_rec);
5687                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
5688                         osd_quota_unpack(obj, rec);
5689         }
5690
5691         iam_it_put(it);
5692         iam_it_fini(it);
5693         osd_ipd_put(env, bag, ipd);
5694
5695         LINVRNT(osd_invariant(obj));
5696
5697         RETURN(rc);
5698 }
5699
5700 static int osd_index_declare_iam_insert(const struct lu_env *env,
5701                                         struct dt_object *dt,
5702                                         const struct dt_rec *rec,
5703                                         const struct dt_key *key,
5704                                         struct thandle *handle)
5705 {
5706         struct osd_thandle *oh;
5707
5708         LASSERT(handle != NULL);
5709
5710         oh = container_of(handle, struct osd_thandle, ot_super);
5711         LASSERT(oh->ot_handle == NULL);
5712
5713         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
5714                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
5715
5716         return 0;
5717 }
5718
5719 /**
5720  *      Inserts (key, value) pair in \a dt index object.
5721  *
5722  *      \param  dt      osd index object
5723  *      \param  key     key for index
5724  *      \param  rec     record reference
5725  *      \param  th      transaction handler
5726  *
5727  *      \retval  0  success
5728  *      \retval -ve failure
5729  */
5730 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
5731                                 const struct dt_rec *rec,
5732                                 const struct dt_key *key, struct thandle *th)
5733 {
5734         struct osd_object *obj = osd_dt_obj(dt);
5735         struct iam_path_descr *ipd;
5736         struct osd_thandle *oh;
5737         struct iam_container *bag;
5738         struct osd_thread_info *oti = osd_oti_get(env);
5739         struct iam_rec *iam_rec;
5740         int rc;
5741
5742         ENTRY;
5743
5744         if (!dt_object_exists(dt))
5745                 RETURN(-ENOENT);
5746
5747         LINVRNT(osd_invariant(obj));
5748         LASSERT(!dt_object_remote(dt));
5749
5750         bag = &obj->oo_dir->od_container;
5751         LASSERT(bag->ic_object == obj->oo_inode);
5752         LASSERT(th != NULL);
5753
5754         osd_trans_exec_op(env, th, OSD_OT_INSERT);
5755
5756         ipd = osd_idx_ipd_get(env, bag);
5757         if (unlikely(ipd == NULL))
5758                 RETURN(-ENOMEM);
5759
5760         oh = container_of(th, struct osd_thandle, ot_super);
5761         LASSERT(oh->ot_handle != NULL);
5762         LASSERT(oh->ot_handle->h_transaction != NULL);
5763         if (S_ISDIR(obj->oo_inode->i_mode)) {
5764                 iam_rec = (struct iam_rec *)oti->oti_ldp;
5765                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec,
5766                              &oti->oti_fid);
5767         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5768                 /* pack quota uid/gid */
5769                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5770                 key = (const struct dt_key *)&oti->oti_quota_id;
5771                 /* pack quota record */
5772                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
5773                 iam_rec = (struct iam_rec *)rec;
5774         } else {
5775                 iam_rec = (struct iam_rec *)rec;
5776         }
5777
5778         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
5779                         iam_rec, ipd);
5780         osd_ipd_put(env, bag, ipd);
5781         LINVRNT(osd_invariant(obj));
5782         osd_trans_exec_check(env, th, OSD_OT_INSERT);
5783         RETURN(rc);
5784 }
5785
5786 /**
5787  * Calls ldiskfs_add_entry() to add directory entry
5788  * into the directory. This is required for
5789  * interoperability mode (b11826)
5790  *
5791  * \retval   0, on success
5792  * \retval -ve, on error
5793  */
5794 static int __osd_ea_add_rec(struct osd_thread_info *info,
5795                             struct osd_object *pobj, struct inode  *cinode,
5796                             const char *name, const struct lu_fid *fid,
5797                             struct htree_lock *hlock, struct thandle *th)
5798 {
5799         struct ldiskfs_dentry_param *ldp;
5800         struct dentry *child;
5801         struct osd_thandle *oth;
5802         struct lu_name ln;
5803         int rc;
5804
5805         oth = container_of(th, struct osd_thandle, ot_super);
5806         LASSERT(oth->ot_handle != NULL);
5807         LASSERT(oth->ot_handle->h_transaction != NULL);
5808         LASSERT(pobj->oo_inode);
5809
5810         rc = obj_name2lu_name(pobj, name, strlen(name), &ln);
5811         if (rc)
5812                 RETURN(rc);
5813
5814         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
5815         if (unlikely(osd_object_is_root(pobj)))
5816                 ldp->edp_magic = 0;
5817         else
5818                 osd_get_ldiskfs_dirent_param(ldp, fid);
5819         child = osd_child_dentry_get(info->oti_env, pobj,
5820                                      ln.ln_name, ln.ln_namelen);
5821         child->d_fsdata = (void *)ldp;
5822         dquot_initialize(pobj->oo_inode);
5823         rc = osd_ldiskfs_add_entry(info, osd_obj2dev(pobj), oth->ot_handle,
5824                                    child, cinode, hlock);
5825         if (rc == 0 && OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_TYPE)) {
5826                 struct ldiskfs_dir_entry_2      *de;
5827                 struct buffer_head              *bh;
5828                 int                              rc1;
5829
5830                 bh = osd_ldiskfs_find_entry(pobj->oo_inode, &child->d_name, &de,
5831                                             NULL, hlock);
5832                 if (!IS_ERR(bh)) {
5833                         rc1 = osd_ldiskfs_journal_get_write_access(
5834                                 oth->ot_handle, pobj->oo_inode->i_sb, bh,
5835                                 LDISKFS_JTR_NONE);
5836                         if (rc1 == 0) {
5837                                 if (S_ISDIR(cinode->i_mode))
5838                                         de->file_type = LDISKFS_DIRENT_LUFID |
5839                                                         LDISKFS_FT_REG_FILE;
5840                                 else
5841                                         de->file_type = LDISKFS_DIRENT_LUFID |
5842                                                         LDISKFS_FT_DIR;
5843                                 ldiskfs_handle_dirty_metadata(oth->ot_handle,
5844                                                               NULL, bh);
5845                         }
5846                         brelse(bh);
5847                 }
5848         }
5849
5850         if (ln.ln_name != name)
5851                 kfree(ln.ln_name);
5852         RETURN(rc);
5853 }
5854
5855 /**
5856  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
5857  * into the directory.Also sets flags into osd object to
5858  * indicate dot and dotdot are created. This is required for
5859  * interoperability mode (b11826)
5860  *
5861  * \param dir   directory for dot and dotdot fixup.
5862  * \param obj   child object for linking
5863  *
5864  * \retval   0, on success
5865  * \retval -ve, on error
5866  */
5867 static int osd_add_dot_dotdot(struct osd_thread_info *info,
5868                               struct osd_object *dir,
5869                               struct inode *parent_dir, const char *name,
5870                               const struct lu_fid *dot_fid,
5871                               const struct lu_fid *dot_dot_fid,
5872                               struct thandle *th)
5873 {
5874         struct inode *inode = dir->oo_inode;
5875         struct osd_thandle *oth;
5876         int result = 0;
5877
5878         oth = container_of(th, struct osd_thandle, ot_super);
5879         LASSERT(oth->ot_handle->h_transaction != NULL);
5880         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
5881
5882         if (strcmp(name, dot) == 0) {
5883                 if (dir->oo_compat_dot_created) {
5884                         result = -EEXIST;
5885                 } else {
5886                         LASSERT(inode->i_ino == parent_dir->i_ino);
5887                         dir->oo_compat_dot_created = 1;
5888                         result = 0;
5889                 }
5890         } else if (strcmp(name, dotdot) == 0) {
5891                 if (!dir->oo_compat_dot_created)
5892                         return -EINVAL;
5893                 /* in case of rename, dotdot is already created */
5894                 if (dir->oo_compat_dotdot_created) {
5895                         return __osd_ea_add_rec(info, dir, parent_dir, name,
5896                                                 dot_dot_fid, NULL, th);
5897                 }
5898
5899                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
5900                         struct lu_fid tfid = *dot_dot_fid;
5901
5902                         tfid.f_oid--;
5903                         result = osd_add_dot_dotdot_internal(info,
5904                                         dir->oo_inode, parent_dir, dot_fid,
5905                                         &tfid, oth);
5906                 } else {
5907                         result = osd_add_dot_dotdot_internal(info,
5908                                         dir->oo_inode, parent_dir, dot_fid,
5909                                         dot_dot_fid, oth);
5910                 }
5911
5912                 if (result == 0)
5913                         dir->oo_compat_dotdot_created = 1;
5914         }
5915
5916         return result;
5917 }
5918
5919
5920 /**
5921  * It will call the appropriate osd_add* function and return the
5922  * value, return by respective functions.
5923  */
5924 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
5925                           struct inode *cinode, const char *name,
5926                           const struct lu_fid *fid, struct thandle *th)
5927 {
5928         struct osd_thread_info *info = osd_oti_get(env);
5929         struct htree_lock *hlock;
5930         int rc;
5931
5932         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
5933
5934         if (name[0] == '.' && (name[1] == '\0' ||
5935                                (name[1] == '.' && name[2] == '\0'))) {
5936                 if (hlock != NULL) {
5937                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5938                                            pobj->oo_inode, 0);
5939                 } else {
5940                         down_write(&pobj->oo_ext_idx_sem);
5941                 }
5942
5943                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
5944                                         lu_object_fid(&pobj->oo_dt.do_lu),
5945                                         fid, th);
5946         } else {
5947                 if (hlock != NULL) {
5948                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5949                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
5950                 } else {
5951                         down_write(&pobj->oo_ext_idx_sem);
5952                 }
5953
5954                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
5955                         struct lu_fid *tfid = &info->oti_fid;
5956
5957                         *tfid = *fid;
5958                         tfid->f_ver = ~0;
5959                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
5960                                               tfid, hlock, th);
5961                 } else {
5962                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
5963                                               hlock, th);
5964                 }
5965         }
5966         if (!rc && fid_is_namespace_visible(lu_object_fid(&pobj->oo_dt.do_lu))
5967             && pobj->oo_dirent_count != LU_DIRENT_COUNT_UNSET)
5968                 pobj->oo_dirent_count++;
5969
5970         if (hlock != NULL)
5971                 ldiskfs_htree_unlock(hlock);
5972         else
5973                 up_write(&pobj->oo_ext_idx_sem);
5974
5975         return rc;
5976 }
5977
5978 static int
5979 osd_ldiskfs_consistency_check(struct osd_thread_info *oti,
5980                               struct osd_device *dev,
5981                               const struct lu_fid *fid,
5982                               struct osd_inode_id *id)
5983 {
5984         struct lustre_scrub *scrub = &dev->od_scrub.os_scrub;
5985         struct inode *inode = NULL;
5986         int once = 0;
5987         bool insert;
5988         int rc;
5989
5990         ENTRY;
5991         if (!scrub_needs_check(scrub, fid, id->oii_ino))
5992                 RETURN(0);
5993 again:
5994         rc = osd_oi_lookup(oti, dev, fid, &oti->oti_id, 0);
5995         if (rc == -ENOENT) {
5996                 __u32 gen = id->oii_gen;
5997
5998                 insert = true;
5999                 if (inode != NULL)
6000                         goto trigger;
6001
6002                 inode = osd_iget(oti, dev, id);
6003                 /* The inode has been removed (by race maybe). */
6004                 if (IS_ERR(inode)) {
6005                         rc = PTR_ERR(inode);
6006
6007                         RETURN(rc == -ESTALE ? -ENOENT : rc);
6008                 }
6009
6010                 /* The OI mapping is lost. */
6011                 if (gen != OSD_OII_NOGEN)
6012                         goto trigger;
6013
6014                 /*
6015                  * The inode may has been reused by others, we do not know,
6016                  * leave it to be handled by subsequent osd_fid_lookup().
6017                  */
6018                 GOTO(out, rc = 0);
6019         } else if (rc || osd_id_eq(id, &oti->oti_id)) {
6020                 GOTO(out, rc);
6021         }
6022
6023         insert = false;
6024
6025 trigger:
6026         if (scrub->os_running) {
6027                 if (inode == NULL) {
6028                         inode = osd_iget(oti, dev, id);
6029                         /* The inode has been removed (by race maybe). */
6030                         if (IS_ERR(inode)) {
6031                                 rc = PTR_ERR(inode);
6032
6033                                 RETURN(rc == -ESTALE ? -ENOENT : rc);
6034                         }
6035                 }
6036
6037                 rc = osd_scrub_oi_insert(dev, fid, id, insert);
6038                 /*
6039                  * There is race condition between osd_oi_lookup and OI scrub.
6040                  * The OI scrub finished just after osd_oi_lookup() failure.
6041                  * Under such case, it is unnecessary to trigger OI scrub again,
6042                  * but try to call osd_oi_lookup() again.
6043                  */
6044                 if (unlikely(rc == -EAGAIN))
6045                         goto again;
6046
6047                 if (!S_ISDIR(inode->i_mode))
6048                         rc = 0;
6049                 else
6050                         rc = osd_check_lmv(oti, dev, inode);
6051
6052                 GOTO(out, rc);
6053         }
6054
6055         if (dev->od_scrub.os_scrub.os_auto_scrub_interval != AS_NEVER &&
6056             ++once == 1) {
6057                 rc = osd_scrub_start(oti->oti_env, dev, SS_AUTO_PARTIAL |
6058                                      SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT);
6059                 CDEBUG_LIMIT(D_LFSCK | D_CONSOLE | D_WARNING,
6060                              "%s: trigger partial OI scrub for RPC inconsistency, checking FID "DFID"/%u: rc = %d\n",
6061                              osd_dev2name(dev), PFID(fid), id->oii_ino, rc);
6062                 if (rc == 0 || rc == -EALREADY)
6063                         goto again;
6064         }
6065
6066         GOTO(out, rc);
6067
6068 out:
6069         iput(inode);
6070
6071         RETURN(rc);
6072 }
6073
6074 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
6075                                struct osd_device *dev,
6076                                struct lu_fid *fid, __u32 ino)
6077 {
6078         struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
6079         struct osd_idmap_cache *oic = &oti->oti_cache;
6080         struct inode *inode;
6081         int rc;
6082
6083         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
6084         inode = osd_iget(oti, dev, &oic->oic_lid);
6085         if (IS_ERR(inode)) {
6086                 fid_zero(&oic->oic_fid);
6087                 return PTR_ERR(inode);
6088         }
6089
6090         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, loa);
6091         iput(inode);
6092         if (rc != 0)
6093                 fid_zero(&oic->oic_fid);
6094         else
6095                 *fid = oic->oic_fid = loa->loa_lma.lma_self_fid;
6096         return rc;
6097 }
6098
6099 void osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
6100                       struct osd_inode_id *id, const struct lu_fid *fid)
6101 {
6102         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
6103                id->oii_ino, id->oii_gen, info);
6104         info->oti_cache.oic_lid = *id;
6105         info->oti_cache.oic_fid = *fid;
6106         info->oti_cache.oic_dev = osd;
6107 }
6108
6109 /**
6110  * Get parent FID from the linkEA.
6111  *
6112  * For a directory which parent resides on remote MDT, to satisfy the
6113  * local e2fsck, we insert it into the /REMOTE_PARENT_DIR locally. On
6114  * the other hand, to make the lookup(..) on the directory can return
6115  * the real parent FID, we append the real parent FID after its ".."
6116  * name entry in the /REMOTE_PARENT_DIR.
6117  *
6118  * Unfortunately, such PFID-in-dirent cannot be preserved via file-level
6119  * backup. So after the restore, we cannot get the right parent FID from
6120  * its ".." name entry in the /REMOTE_PARENT_DIR. Under such case, since
6121  * we have stored the real parent FID in the directory object's linkEA,
6122  * we can parse the linkEA for the real parent FID.
6123  *
6124  * \param[in] env       pointer to the thread context
6125  * \param[in] obj       pointer to the object to be handled
6126  * \param[out]fid       pointer to the buffer to hold the parent FID
6127  *
6128  * \retval              0 for getting the real parent FID successfully
6129  * \retval              negative error number on failure
6130  */
6131 static int osd_get_pfid_from_linkea(const struct lu_env *env,
6132                                     struct osd_object *obj,
6133                                     struct lu_fid *fid)
6134 {
6135         struct osd_thread_info *oti = osd_oti_get(env);
6136         struct lu_buf *buf = &oti->oti_big_buf;
6137         struct dentry *dentry = &oti->oti_obj_dentry;
6138         struct inode *inode = obj->oo_inode;
6139         struct linkea_data ldata = { NULL };
6140         int rc;
6141
6142         ENTRY;
6143
6144         fid_zero(fid);
6145         if (!S_ISDIR(inode->i_mode))
6146                 RETURN(-EIO);
6147
6148 again:
6149         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6150                              buf->lb_buf, buf->lb_len);
6151         if (rc == -ERANGE) {
6152                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6153                                      NULL, 0);
6154                 if (rc > 0) {
6155                         lu_buf_realloc(buf, rc);
6156                         if (buf->lb_buf == NULL)
6157                                 RETURN(-ENOMEM);
6158
6159                         goto again;
6160                 }
6161         }
6162
6163         if (unlikely(rc == 0))
6164                 RETURN(-ENODATA);
6165
6166         if (rc < 0)
6167                 RETURN(rc);
6168
6169         if (unlikely(buf->lb_buf == NULL)) {
6170                 lu_buf_realloc(buf, rc);
6171                 if (buf->lb_buf == NULL)
6172                         RETURN(-ENOMEM);
6173
6174                 goto again;
6175         }
6176
6177         ldata.ld_buf = buf;
6178         rc = linkea_init_with_rec(&ldata);
6179         if (!rc) {
6180                 linkea_first_entry(&ldata);
6181                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, NULL, fid);
6182         }
6183
6184         RETURN(rc);
6185 }
6186
6187 static int osd_verify_ent_by_linkea(const struct lu_env *env,
6188                                     struct inode *inode,
6189                                     const struct lu_fid *pfid,
6190                                     const char *name, const int namelen)
6191 {
6192         struct osd_thread_info *oti = osd_oti_get(env);
6193         struct lu_buf *buf = &oti->oti_big_buf;
6194         struct dentry *dentry = &oti->oti_obj_dentry;
6195         struct linkea_data ldata = { NULL };
6196         struct lu_name cname = { .ln_name = name,
6197                                  .ln_namelen = namelen };
6198         int rc;
6199
6200         ENTRY;
6201
6202 again:
6203         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6204                              buf->lb_buf, buf->lb_len);
6205         if (rc == -ERANGE)
6206                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK, NULL, 0);
6207
6208         if (rc < 0)
6209                 RETURN(rc);
6210
6211         if (unlikely(rc == 0))
6212                 RETURN(-ENODATA);
6213
6214         if (buf->lb_len < rc) {
6215                 lu_buf_realloc(buf, rc);
6216                 if (buf->lb_buf == NULL)
6217                         RETURN(-ENOMEM);
6218
6219                 goto again;
6220         }
6221
6222         ldata.ld_buf = buf;
6223         rc = linkea_init_with_rec(&ldata);
6224         if (!rc)
6225                 rc = linkea_links_find(&ldata, &cname, pfid);
6226
6227         RETURN(rc);
6228 }
6229
6230 /**
6231  * Calls ->lookup() to find dentry. From dentry get inode and
6232  * read inode's ea to get fid. This is required for  interoperability
6233  * mode (b11826)
6234  *
6235  * \retval   0, on success
6236  * \retval -ve, on error
6237  */
6238 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
6239                              struct dt_rec *rec, const struct dt_key *key)
6240 {
6241         struct inode *dir = obj->oo_inode;
6242         struct dentry *dentry;
6243         struct ldiskfs_dir_entry_2 *de;
6244         struct buffer_head *bh;
6245         struct lu_fid *fid = (struct lu_fid *)rec;
6246         struct htree_lock *hlock = NULL;
6247         struct lu_name ln;
6248         int ino;
6249         int rc;
6250
6251         ENTRY;
6252
6253         LASSERT(dir->i_op != NULL);
6254         LASSERT(dir->i_op->lookup != NULL);
6255
6256         rc = obj_name2lu_name(obj, (char *)key, strlen((char *)key), &ln);
6257         if (rc)
6258                 RETURN(rc);
6259
6260         dentry = osd_child_dentry_get(env, obj, ln.ln_name, ln.ln_namelen);
6261
6262         if (obj->oo_hl_head != NULL) {
6263                 hlock = osd_oti_get(env)->oti_hlock;
6264                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
6265                                    dir, LDISKFS_HLOCK_LOOKUP);
6266         } else {
6267                 down_read(&obj->oo_ext_idx_sem);
6268         }
6269
6270         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
6271         if (!IS_ERR(bh)) {
6272                 struct osd_thread_info *oti = osd_oti_get(env);
6273                 struct osd_inode_id *id = &oti->oti_id;
6274                 struct osd_device *dev = osd_obj2dev(obj);
6275
6276                 ino = le32_to_cpu(de->inode);
6277                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
6278                         brelse(bh);
6279                         rc = osd_fail_fid_lookup(oti, dev, fid, ino);
6280                         GOTO(out, rc);
6281                 }
6282
6283                 rc = osd_get_fid_from_dentry(de, rec);
6284
6285                 /* done with de, release bh */
6286                 brelse(bh);
6287                 if (rc != 0) {
6288                         if (unlikely(is_remote_parent_ino(dev, ino))) {
6289                                 const char *name = (const char *)key;
6290
6291                                 /*
6292                                  * If the parent is on remote MDT, and there
6293                                  * is no FID-in-dirent, then we have to get
6294                                  * the parent FID from the linkEA.
6295                                  */
6296                                 if (likely(strlen(name) == 2 &&
6297                                            name[0] == '.' && name[1] == '.'))
6298                                         rc = osd_get_pfid_from_linkea(env, obj,
6299                                                                       fid);
6300                         } else {
6301                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
6302                         }
6303                 } else {
6304                         osd_id_gen(id, ino, OSD_OII_NOGEN);
6305                 }
6306
6307                 if (rc != 0 || osd_remote_fid(env, dev, fid))
6308                         GOTO(out, rc);
6309
6310                 rc = osd_ldiskfs_consistency_check(oti, dev, fid, id);
6311                 if (rc != -ENOENT) {
6312                         /* Other error should not affect lookup result. */
6313                         rc = 0;
6314
6315                         /* Normal file mapping should be added into OI cache
6316                          * after FID in LMA check, but for local files like
6317                          * hsm_actions, their FIDs are not stored in OI files,
6318                          * see osd_initial_OI_scrub(), and here is the only
6319                          * place to load mapping into OI cache.
6320                          */
6321                         if (!fid_is_namespace_visible(fid))
6322                                 osd_add_oi_cache(osd_oti_get(env),
6323                                                  osd_obj2dev(obj), id, fid);
6324                 }
6325                 CDEBUG(D_INODE, DFID"/"DNAME" => "DFID"\n",
6326                        PFID(lu_object_fid(&obj->oo_dt.do_lu)), PNAME(&ln),
6327                        PFID(fid));
6328         } else {
6329                 rc = PTR_ERR(bh);
6330         }
6331
6332         GOTO(out, rc);
6333
6334 out:
6335         if (hlock != NULL)
6336                 ldiskfs_htree_unlock(hlock);
6337         else
6338                 up_read(&obj->oo_ext_idx_sem);
6339         if (ln.ln_name != (char *)key)
6340                 kfree(ln.ln_name);
6341         RETURN(rc);
6342 }
6343
6344 static int osd_index_declare_ea_insert(const struct lu_env *env,
6345                                        struct dt_object *dt,
6346                                        const struct dt_rec *rec,
6347                                        const struct dt_key *key,
6348                                        struct thandle *handle)
6349 {
6350         struct osd_thandle *oh;
6351         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
6352         struct dt_insert_rec *rec1 = (struct dt_insert_rec *)rec;
6353         const struct lu_fid *fid = rec1->rec_fid;
6354         int credits, rc = 0;
6355         struct osd_idmap_cache *idc;
6356
6357         ENTRY;
6358
6359         LASSERT(!dt_object_remote(dt));
6360         LASSERT(handle != NULL);
6361         LASSERT(fid != NULL);
6362         LASSERT(rec1->rec_type != 0);
6363
6364         oh = container_of(handle, struct osd_thandle, ot_super);
6365         LASSERT(oh->ot_handle == NULL);
6366
6367         credits = osd_dto_credits_noquota[DTO_INDEX_INSERT];
6368
6369         /*
6370          * we can't call iget() while a transactions is running
6371          * (this can lead to a deadlock), but we need to know
6372          * inum and object type. so we find this information at
6373          * declaration and cache in per-thread info
6374          */
6375         idc = osd_idc_find_or_init(env, osd, fid);
6376         if (IS_ERR(idc))
6377                 RETURN(PTR_ERR(idc));
6378         if (idc->oic_remote) {
6379                 /*
6380                  * a reference to remote inode is represented by an
6381                  * agent inode which we have to create
6382                  */
6383                 credits += osd_dto_credits_noquota[DTO_OBJECT_CREATE];
6384                 credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
6385         }
6386
6387         osd_trans_declare_op(env, oh, OSD_OT_INSERT, credits);
6388
6389         if (osd_dt_obj(dt)->oo_inode != NULL) {
6390                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
6391
6392                 /*
6393                  * We ignore block quota on meta pool (MDTs), so needn't
6394                  * calculate how many blocks will be consumed by this index
6395                  * insert
6396                  */
6397                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
6398                                            i_gid_read(inode),
6399                                            i_projid_read(inode), 0,
6400                                            oh, osd_dt_obj(dt), NULL,
6401                                            OSD_QID_BLK);
6402                 if (rc)
6403                         RETURN(rc);
6404
6405 #ifdef HAVE_PROJECT_QUOTA
6406                 /*
6407                  * Reserve credits for local agent inode to transfer
6408                  * to 0, quota enforcement is ignored in this case.
6409                  */
6410                 if (idc->oic_remote &&
6411                     LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
6412                     i_projid_read(inode) != 0)
6413                         rc = osd_declare_attr_qid(env, osd_dt_obj(dt), oh,
6414                                                   0, i_projid_read(inode),
6415                                                   0, false, PRJQUOTA);
6416 #endif
6417         }
6418
6419         RETURN(rc);
6420 }
6421
6422 /**
6423  * Index add function for interoperability mode (b11826).
6424  * It will add the directory entry.This entry is needed to
6425  * maintain name->fid mapping.
6426  *
6427  * \param key it is key i.e. file entry to be inserted
6428  * \param rec it is value of given key i.e. fid
6429  *
6430  * \retval   0, on success
6431  * \retval -ve, on error
6432  */
6433 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
6434                                const struct dt_rec *rec,
6435                                const struct dt_key *key, struct thandle *th)
6436 {
6437         struct osd_object *obj = osd_dt_obj(dt);
6438         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
6439         struct dt_insert_rec *rec1 = (struct dt_insert_rec *)rec;
6440         const struct lu_fid *fid = rec1->rec_fid;
6441         const char *name = (const char *)key;
6442         struct osd_thread_info *oti = osd_oti_get(env);
6443         struct inode *child_inode = NULL;
6444         struct osd_idmap_cache *idc;
6445         int rc;
6446
6447         ENTRY;
6448
6449         if (!dt_object_exists(dt))
6450                 RETURN(-ENOENT);
6451
6452         LASSERT(osd_invariant(obj));
6453         LASSERT(!dt_object_remote(dt));
6454         LASSERT(th != NULL);
6455
6456         osd_trans_exec_op(env, th, OSD_OT_INSERT);
6457
6458         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!\n", PFID(fid));
6459
6460         idc = osd_idc_find(env, osd, fid);
6461         if (unlikely(idc == NULL)) {
6462                 idc = osd_idc_find_or_init(env, osd, fid);
6463                 if (IS_ERR(idc)) {
6464                         /*
6465                          * this dt_insert() wasn't declared properly, so
6466                          * FID is missing in OI cache. we better do not
6467                          * lookup FID in FLDB/OI and don't risk to deadlock,
6468                          * but in some special cases (lfsck testing, etc)
6469                          * it's much simpler than fixing a caller.
6470                          *
6471                          * normally this error should be placed after the first
6472                          * find, but migrate may attach source stripes to
6473                          * target, which doesn't create stripes.
6474                          */
6475                         CERROR("%s: "DFID" wasn't declared for insert\n",
6476                                osd_name(osd), PFID(fid));
6477                         dump_stack();
6478                         RETURN(PTR_ERR(idc));
6479                 }
6480         }
6481
6482         if (idc->oic_remote) {
6483                 /* Insert remote entry */
6484                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
6485                         child_inode =
6486                         igrab(osd->od_mdt_map->omm_remote_parent->d_inode);
6487                 } else {
6488                         child_inode = osd_create_local_agent_inode(env, osd,
6489                                         obj, fid, rec1->rec_type & S_IFMT, th);
6490                         if (IS_ERR(child_inode))
6491                                 RETURN(PTR_ERR(child_inode));
6492                 }
6493         } else {
6494                 /* Insert local entry */
6495                 if (unlikely(idc->oic_lid.oii_ino == 0)) {
6496                         /* for a reason OI cache wasn't filled properly */
6497                         CERROR("%s: OIC for "DFID" isn't filled\n",
6498                                osd_name(osd), PFID(fid));
6499                         RETURN(-EINVAL);
6500                 }
6501                 child_inode = oti->oti_inode;
6502                 if (unlikely(child_inode == NULL)) {
6503                         struct ldiskfs_inode_info *lii;
6504
6505                         OBD_ALLOC_PTR(lii);
6506                         if (lii == NULL)
6507                                 RETURN(-ENOMEM);
6508                         child_inode = oti->oti_inode = &lii->vfs_inode;
6509                 }
6510                 child_inode->i_sb = osd_sb(osd);
6511                 child_inode->i_ino = idc->oic_lid.oii_ino;
6512                 child_inode->i_mode = rec1->rec_type & S_IFMT;
6513         }
6514
6515         rc = osd_ea_add_rec(env, obj, child_inode, name, fid, th);
6516
6517         CDEBUG(D_INODE, "parent %lu insert %s:%lu rc = %d\n",
6518                obj->oo_inode->i_ino, name, child_inode->i_ino, rc);
6519
6520         if (child_inode && child_inode != oti->oti_inode)
6521                 iput(child_inode);
6522         LASSERT(osd_invariant(obj));
6523         osd_trans_exec_check(env, th, OSD_OT_INSERT);
6524
6525         RETURN(rc);
6526 }
6527
6528 /**
6529  *  Initialize osd Iterator for given osd index object.
6530  *
6531  *  \param  dt      osd index object
6532  */
6533
6534 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
6535                                      struct dt_object *dt,
6536                                      __u32 unused)
6537 {
6538         struct osd_it_iam *it;
6539         struct osd_object *obj = osd_dt_obj(dt);
6540         struct lu_object *lo = &dt->do_lu;
6541         struct iam_path_descr *ipd;
6542         struct iam_container *bag = &obj->oo_dir->od_container;
6543
6544         if (!dt_object_exists(dt))
6545                 return ERR_PTR(-ENOENT);
6546
6547         OBD_ALLOC_PTR(it);
6548         if (it == NULL)
6549                 return ERR_PTR(-ENOMEM);
6550
6551         ipd = osd_it_ipd_get(env, bag);
6552         if (likely(ipd != NULL)) {
6553                 it->oi_obj = obj;
6554                 it->oi_ipd = ipd;
6555                 lu_object_get(lo);
6556                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
6557                 return (struct dt_it *)it;
6558         } else {
6559                 OBD_FREE_PTR(it);
6560                 return ERR_PTR(-ENOMEM);
6561         }
6562 }
6563
6564 /**
6565  * free given Iterator.
6566  */
6567 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
6568 {
6569         struct osd_it_iam *it  = (struct osd_it_iam *)di;
6570         struct osd_object *obj = it->oi_obj;
6571
6572         iam_it_fini(&it->oi_it);
6573         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
6574         osd_object_put(env, obj);
6575         OBD_FREE_PTR(it);
6576 }
6577
6578 /**
6579  *  Move Iterator to record specified by \a key
6580  *
6581  *  \param  di      osd iterator
6582  *  \param  key     key for index
6583  *
6584  *  \retval +ve  di points to record with least key not larger than key
6585  *  \retval  0   di points to exact matched key
6586  *  \retval -ve  failure
6587  */
6588
6589 static int osd_it_iam_get(const struct lu_env *env,
6590                           struct dt_it *di, const struct dt_key *key)
6591 {
6592         struct osd_thread_info *oti = osd_oti_get(env);
6593         struct osd_it_iam *it = (struct osd_it_iam *)di;
6594
6595         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
6596                 /* swab quota uid/gid */
6597                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
6598                 key = (struct dt_key *)&oti->oti_quota_id;
6599         }
6600
6601         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
6602 }
6603
6604 /**
6605  *  Release Iterator
6606  *
6607  *  \param  di      osd iterator
6608  */
6609 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
6610 {
6611         struct osd_it_iam *it = (struct osd_it_iam *)di;
6612
6613         iam_it_put(&it->oi_it);
6614 }
6615
6616 /**
6617  *  Move iterator by one record
6618  *
6619  *  \param  di      osd iterator
6620  *
6621  *  \retval +1   end of container reached
6622  *  \retval  0   success
6623  *  \retval -ve  failure
6624  */
6625
6626 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
6627 {
6628         struct osd_it_iam *it = (struct osd_it_iam *)di;
6629
6630         return iam_it_next(&it->oi_it);
6631 }
6632
6633 /**
6634  * Return pointer to the key under iterator.
6635  */
6636
6637 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
6638                                      const struct dt_it *di)
6639 {
6640         struct osd_thread_info *oti = osd_oti_get(env);
6641         struct osd_it_iam *it = (struct osd_it_iam *)di;
6642         struct osd_object *obj = it->oi_obj;
6643         struct dt_key *key;
6644
6645         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
6646
6647         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
6648                 /* swab quota uid/gid */
6649                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
6650                 key = (struct dt_key *)&oti->oti_quota_id;
6651         }
6652
6653         return key;
6654 }
6655
6656 /**
6657  * Return size of key under iterator (in bytes)
6658  */
6659
6660 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
6661 {
6662         struct osd_it_iam *it = (struct osd_it_iam *)di;
6663
6664         return iam_it_key_size(&it->oi_it);
6665 }
6666
6667 static inline void
6668 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
6669 {
6670         /* check if file type is required */
6671         if (ent->lde_attrs & LUDA_TYPE) {
6672                 struct luda_type *lt;
6673                 int align = sizeof(*lt) - 1;
6674
6675                 len = (len + align) & ~align;
6676                 lt = (struct luda_type *)(ent->lde_name + len);
6677                 lt->lt_type = cpu_to_le16(DTTOIF(type));
6678         }
6679
6680         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
6681 }
6682
6683 /**
6684  * build lu direct from backend fs dirent.
6685  */
6686
6687 static inline void
6688 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
6689                    char *name, __u16 namelen, __u16 type, __u32 attr)
6690 {
6691         ent->lde_attrs = attr | LUDA_FID;
6692         fid_cpu_to_le(&ent->lde_fid, fid);
6693
6694         ent->lde_hash = cpu_to_le64(offset);
6695         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
6696
6697         strncpy(ent->lde_name, name, namelen);
6698         ent->lde_name[namelen] = '\0';
6699         ent->lde_namelen = cpu_to_le16(namelen);
6700
6701         /* append lustre attributes */
6702         osd_it_append_attrs(ent, namelen, type);
6703 }
6704
6705 /**
6706  * Return pointer to the record under iterator.
6707  */
6708 static int osd_it_iam_rec(const struct lu_env *env,
6709                           const struct dt_it *di,
6710                           struct dt_rec *dtrec, __u32 attr)
6711 {
6712         struct osd_it_iam *it = (struct osd_it_iam *)di;
6713         struct osd_thread_info *info = osd_oti_get(env);
6714
6715         ENTRY;
6716
6717         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
6718                 const struct osd_fid_pack *rec;
6719                 struct lu_fid *fid = &info->oti_fid;
6720                 struct lu_dirent *lde = (struct lu_dirent *)dtrec;
6721                 char *name;
6722                 int namelen;
6723                 __u64 hash;
6724                 int rc;
6725
6726                 name = (char *)iam_it_key_get(&it->oi_it);
6727                 if (IS_ERR(name))
6728                         RETURN(PTR_ERR(name));
6729
6730                 namelen = iam_it_key_size(&it->oi_it);
6731
6732                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
6733                 if (IS_ERR(rec))
6734                         RETURN(PTR_ERR(rec));
6735
6736                 rc = osd_fid_unpack(fid, rec);
6737                 if (rc)
6738                         RETURN(rc);
6739
6740                 hash = iam_it_store(&it->oi_it);
6741
6742                 /* IAM does not store object type in IAM index (dir) */
6743                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
6744                                    0, LUDA_FID);
6745         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
6746                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
6747                            (struct iam_rec *)dtrec);
6748                 osd_quota_unpack(it->oi_obj, dtrec);
6749         } else {
6750                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
6751                            (struct iam_rec *)dtrec);
6752         }
6753
6754         RETURN(0);
6755 }
6756
6757 /**
6758  * Returns cookie for current Iterator position.
6759  */
6760 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
6761 {
6762         struct osd_it_iam *it = (struct osd_it_iam *)di;
6763
6764         return iam_it_store(&it->oi_it);
6765 }
6766
6767 /**
6768  * Restore iterator from cookie.
6769  *
6770  * \param  di      osd iterator
6771  * \param  hash    Iterator location cookie
6772  *
6773  * \retval +ve  di points to record with least key not larger than key.
6774  * \retval  0   di points to exact matched key
6775  * \retval -ve  failure
6776  */
6777
6778 static int osd_it_iam_load(const struct lu_env *env,
6779                            const struct dt_it *di, __u64 hash)
6780 {
6781         struct osd_it_iam *it = (struct osd_it_iam *)di;
6782
6783         return iam_it_load(&it->oi_it, hash);
6784 }
6785
6786 static const struct dt_index_operations osd_index_iam_ops = {
6787         .dio_lookup         = osd_index_iam_lookup,
6788         .dio_declare_insert = osd_index_declare_iam_insert,
6789         .dio_insert         = osd_index_iam_insert,
6790         .dio_declare_delete = osd_index_declare_iam_delete,
6791         .dio_delete         = osd_index_iam_delete,
6792         .dio_it     = {
6793                 .init     = osd_it_iam_init,
6794                 .fini     = osd_it_iam_fini,
6795                 .get      = osd_it_iam_get,
6796                 .put      = osd_it_iam_put,
6797                 .next     = osd_it_iam_next,
6798                 .key      = osd_it_iam_key,
6799                 .key_size = osd_it_iam_key_size,
6800                 .rec      = osd_it_iam_rec,
6801                 .store    = osd_it_iam_store,
6802                 .load     = osd_it_iam_load
6803         }
6804 };
6805
6806 struct osd_it_ea *osd_it_dir_init(const struct lu_env *env,
6807                                   struct osd_device *dev,
6808                                   struct inode *inode, u32 attr)
6809 {
6810         struct osd_thread_info *info = osd_oti_get(env);
6811         struct osd_it_ea *oie;
6812         struct file *file;
6813
6814         ENTRY;
6815         file = alloc_file_pseudo(inode, dev->od_mnt, "/", O_NOATIME,
6816                                  inode->i_fop);
6817         if (IS_ERR(file))
6818                 RETURN(ERR_CAST(file));
6819
6820         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
6821         if (attr & LUDA_64BITHASH)
6822                 file->f_mode |= FMODE_64BITHASH;
6823         else
6824                 file->f_mode |= FMODE_32BITHASH;
6825         ihold(inode);
6826
6827         OBD_SLAB_ALLOC_PTR(oie, osd_itea_cachep);
6828         if (!oie)
6829                 goto out_fput;
6830
6831         oie->oie_rd_dirent       = 0;
6832         oie->oie_it_dirent       = 0;
6833         oie->oie_dirent          = NULL;
6834         if (unlikely(!info->oti_it_ea_buf_used)) {
6835                 oie->oie_buf = info->oti_it_ea_buf;
6836                 info->oti_it_ea_buf_used = 1;
6837         } else {
6838                 OBD_ALLOC(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6839                 if (!oie->oie_buf)
6840                         goto out_free;
6841         }
6842         oie->oie_obj = NULL;
6843         oie->oie_file = file;
6844
6845         RETURN(oie);
6846
6847 out_free:
6848         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
6849 out_fput:
6850         fput(file);
6851
6852         return ERR_PTR(-ENOMEM);
6853 }
6854
6855 /**
6856  * Creates or initializes iterator context.
6857  *
6858  * \retval struct osd_it_ea, iterator structure on success
6859  *
6860  */
6861 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
6862                                     struct dt_object *dt,
6863                                     __u32 attr)
6864 {
6865         struct osd_object *obj = osd_dt_obj(dt);
6866         struct osd_device *dev = osd_obj2dev(obj);
6867         struct lu_object *lo = &dt->do_lu;
6868         struct osd_it_ea *oie;
6869
6870         ENTRY;
6871
6872         if (!dt_object_exists(dt) || obj->oo_destroyed)
6873                 RETURN(ERR_PTR(-ENOENT));
6874
6875         oie = osd_it_dir_init(env, dev, obj->oo_inode, attr);
6876         if (IS_ERR(oie))
6877                 RETURN(ERR_CAST(oie));
6878
6879         oie->oie_obj = obj;
6880         lu_object_get(lo);
6881         RETURN((struct dt_it *)oie);
6882 }
6883
6884 void osd_it_dir_fini(const struct lu_env *env, struct osd_it_ea *oie,
6885                      struct inode *inode)
6886 {
6887         struct osd_thread_info *info = osd_oti_get(env);
6888
6889         ENTRY;
6890         fput(oie->oie_file);
6891         if (unlikely(oie->oie_buf != info->oti_it_ea_buf))
6892                 OBD_FREE(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6893         else
6894                 info->oti_it_ea_buf_used = 0;
6895         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
6896         EXIT;
6897 }
6898
6899 /**
6900  * Destroy or finishes iterator context.
6901  *
6902  * \param di iterator structure to be destroyed
6903  */
6904 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
6905 {
6906         struct osd_it_ea *oie = (struct osd_it_ea *)di;
6907         struct osd_object *obj = oie->oie_obj;
6908         struct inode *inode = obj->oo_inode;
6909
6910         ENTRY;
6911         osd_it_dir_fini(env, (struct osd_it_ea *)di, inode);
6912         osd_object_put(env, obj);
6913         EXIT;
6914 }
6915
6916 /**
6917  * It position the iterator at given key, so that next lookup continues from
6918  * that key Or it is similar to dio_it->load() but based on a key,
6919  * rather than file position.
6920  *
6921  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
6922  * to the beginning.
6923  *
6924  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
6925  */
6926 static int osd_it_ea_get(const struct lu_env *env,
6927                          struct dt_it *di, const struct dt_key *key)
6928 {
6929         struct osd_it_ea *it = (struct osd_it_ea *)di;
6930
6931         ENTRY;
6932         LASSERT(((const char *)key)[0] == '\0');
6933         it->oie_file->f_pos = 0;
6934         it->oie_rd_dirent = 0;
6935         it->oie_it_dirent = 0;
6936         it->oie_dirent = NULL;
6937
6938         RETURN(+1);
6939 }
6940
6941 /**
6942  * Does nothing
6943  */
6944 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
6945 {
6946 }
6947
6948 struct osd_filldir_cbs {
6949         struct dir_context ctx;
6950         struct osd_it_ea  *it;
6951 };
6952 /**
6953  * It is called internally by ->iterate*(). It fills the
6954  * iterator's in-memory data structure with required
6955  * information i.e. name, namelen, rec_size etc.
6956  *
6957  * \param buf in which information to be filled in.
6958  * \param name name of the file in given dir
6959  *
6960  * \retval 0 on success
6961  * \retval 1 on buffer full
6962  */
6963 #ifdef HAVE_FILLDIR_USE_CTX
6964 static int osd_ldiskfs_filldir(struct dir_context *ctx,
6965 #else
6966 static int osd_ldiskfs_filldir(void *ctx,
6967 #endif
6968                                const char *name, int namelen,
6969                                loff_t offset, __u64 ino, unsigned int d_type)
6970 {
6971         struct osd_it_ea *it = ((struct osd_filldir_cbs *)ctx)->it;
6972         struct osd_object *obj = it->oie_obj;
6973         struct osd_it_ea_dirent *ent = it->oie_dirent;
6974         struct lu_fid *fid = &ent->oied_fid;
6975         char *buf = it->oie_buf;
6976         struct osd_fid_pack *rec;
6977         ENTRY;
6978
6979         /* this should never happen */
6980         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
6981                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
6982                 RETURN(-EIO);
6983         }
6984
6985         /* Check for enough space. Note oied_name is not NUL terminated. */
6986         if (&ent->oied_name[namelen] > buf + OSD_IT_EA_BUFSIZE)
6987                 RETURN(1);
6988
6989         /* "." is just the object itself. */
6990         if (namelen == 1 && name[0] == '.') {
6991                 if (obj != NULL)
6992                         *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
6993         } else if (d_type & LDISKFS_DIRENT_LUFID) {
6994                 rec = (struct osd_fid_pack *)(name + namelen + 1);
6995                 if (osd_fid_unpack(fid, rec) != 0)
6996                         fid_zero(fid);
6997         } else {
6998                 fid_zero(fid);
6999         }
7000         d_type &= ~LDISKFS_DIRENT_LUFID;
7001
7002         /* NOT export local root. */
7003         if (obj != NULL &&
7004             unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
7005                 ino = obj->oo_inode->i_ino;
7006                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
7007         }
7008
7009         if (obj == NULL || !(obj->oo_lma_flags & LUSTRE_ENCRYPT_FL)) {
7010                 ent->oied_namelen = namelen;
7011                 memcpy(ent->oied_name, name, namelen);
7012         } else {
7013                 int encoded_namelen = critical_chars(name, namelen);
7014
7015                 /* Check again for enough space. */
7016                 if (&ent->oied_name[encoded_namelen] > buf + OSD_IT_EA_BUFSIZE)
7017                         RETURN(1);
7018
7019                 ent->oied_namelen = encoded_namelen;
7020
7021                 if (encoded_namelen == namelen)
7022                         memcpy(ent->oied_name, name, namelen);
7023                 else
7024                         critical_encode(name, namelen, ent->oied_name);
7025         }
7026
7027         ent->oied_ino     = ino;
7028         ent->oied_off     = offset;
7029         ent->oied_type    = d_type;
7030
7031         it->oie_rd_dirent++;
7032         it->oie_dirent = (void *)ent + cfs_size_round(sizeof(*ent) + ent->oied_namelen);
7033         RETURN(0);
7034 }
7035
7036 /**
7037  * Calls ->iterate*() to load a directory entry at a time
7038  * and stored it in iterator's in-memory data structure.
7039  *
7040  * \param di iterator's in memory structure
7041  *
7042  * \retval   0 on success
7043  * \retval -ve on error
7044  * \retval +1 reach the end of entry
7045  */
7046 int osd_ldiskfs_it_fill(const struct lu_env *env, const struct dt_it *di)
7047 {
7048         struct osd_it_ea *it = (struct osd_it_ea *)di;
7049         struct osd_object *obj = it->oie_obj;
7050         struct htree_lock *hlock = NULL;
7051         struct file *filp = it->oie_file;
7052         int rc = 0;
7053         struct osd_filldir_cbs buf = {
7054                 .ctx.actor = osd_ldiskfs_filldir,
7055                 .it = it
7056         };
7057
7058         ENTRY;
7059         it->oie_dirent = it->oie_buf;
7060         it->oie_rd_dirent = 0;
7061
7062         if (obj) {
7063                 if (obj->oo_hl_head != NULL) {
7064                         hlock = osd_oti_get(env)->oti_hlock;
7065                         ldiskfs_htree_lock(hlock, obj->oo_hl_head,
7066                                            obj->oo_inode,
7067                                            LDISKFS_HLOCK_READDIR);
7068                 } else {
7069                         down_read(&obj->oo_ext_idx_sem);
7070                 }
7071         }
7072
7073         rc = iterate_dir(filp, &buf.ctx);
7074         if (rc)
7075                 GOTO(unlock, rc);
7076
7077         if (it->oie_rd_dirent == 0) {
7078                 /*
7079                  * If it does not get any dirent, it means it has been reached
7080                  * to the end of the dir
7081                  */
7082                 it->oie_file->f_pos = ldiskfs_get_htree_eof(it->oie_file);
7083                 if (rc == 0)
7084                         rc = 1;
7085         } else {
7086                 it->oie_dirent = it->oie_buf;
7087                 it->oie_it_dirent = 1;
7088         }
7089 unlock:
7090         if (obj) {
7091                 if (hlock != NULL)
7092                         ldiskfs_htree_unlock(hlock);
7093                 else
7094                         up_read(&obj->oo_ext_idx_sem);
7095         }
7096
7097         RETURN(rc);
7098 }
7099
7100 /**
7101  * It calls osd_ldiskfs_it_fill() which will use ->iterate*()
7102  * to load a directory entry at a time and stored it in
7103  * iterator's in-memory data structure.
7104  *
7105  * \param di iterator's in memory structure
7106  *
7107  * \retval +ve iterator reached to end
7108  * \retval   0 iterator not reached to end
7109  * \retval -ve on error
7110  */
7111 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
7112 {
7113         struct osd_it_ea *it = (struct osd_it_ea *)di;
7114         int rc;
7115
7116         ENTRY;
7117
7118         if (it->oie_it_dirent < it->oie_rd_dirent) {
7119                 it->oie_dirent =
7120                         (void *)it->oie_dirent +
7121                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
7122                                        it->oie_dirent->oied_namelen);
7123                 it->oie_it_dirent++;
7124                 rc = 0;
7125         } else {
7126                 if (it->oie_file->f_pos == ldiskfs_get_htree_eof(it->oie_file))
7127                         rc = 1;
7128                 else
7129                         rc = osd_ldiskfs_it_fill(env, di);
7130         }
7131
7132         RETURN(rc);
7133 }
7134
7135 /**
7136  * Returns the key at current position from iterator's in memory structure.
7137  *
7138  * \param di iterator's in memory structure
7139  *
7140  * \retval key i.e. struct dt_key on success
7141  */
7142 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
7143                                     const struct dt_it *di)
7144 {
7145         struct osd_it_ea *it = (struct osd_it_ea *)di;
7146
7147         return (struct dt_key *)it->oie_dirent->oied_name;
7148 }
7149
7150 /**
7151  * Returns key's size at current position from iterator's in memory structure.
7152  *
7153  * \param di iterator's in memory structure
7154  *
7155  * \retval key_size i.e. struct dt_key on success
7156  */
7157 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
7158 {
7159         struct osd_it_ea *it = (struct osd_it_ea *)di;
7160
7161         return it->oie_dirent->oied_namelen;
7162 }
7163
7164 #if defined LDISKFS_DIR_ENTRY_LEN && defined LDISKFS_DIR_ENTRY_LEN_
7165 #undef LDISKFS_DIR_REC_LEN
7166 # if defined LDISKFS_DIR_REC_LEN_WITH_DIR
7167 #  define LDISKFS_DIR_REC_LEN(de, dir)  LDISKFS_DIR_ENTRY_LEN_((de), (dir))
7168 # else
7169 #  define LDISKFS_DIR_REC_LEN(de)       LDISKFS_DIR_ENTRY_LEN_((de))
7170 # endif
7171 #endif
7172
7173 #if defined LDISKFS_DIR_REC_LEN_WITH_DIR
7174 # define LDISKFS_DIR_REC_LEN_DIR(de)    LDISKFS_DIR_REC_LEN((de), NULL)
7175 #else
7176 # define LDISKFS_DIR_REC_LEN_DIR(de)    LDISKFS_DIR_REC_LEN((de))
7177 #endif
7178
7179 static inline bool osd_dotdot_has_space(struct ldiskfs_dir_entry_2 *de)
7180 {
7181         if (LDISKFS_DIR_REC_LEN_DIR(de) >=
7182             __LDISKFS_DIR_REC_LEN(2 + 1 + sizeof(struct osd_fid_pack)))
7183                 return true;
7184
7185         return false;
7186 }
7187
7188 static inline bool
7189 osd_dirent_has_space(struct ldiskfs_dir_entry_2 *de, __u16 namelen,
7190                      unsigned int blocksize, bool dotdot)
7191 {
7192         if (dotdot)
7193                 return osd_dotdot_has_space(de);
7194
7195         if (ldiskfs_rec_len_from_disk(de->rec_len, blocksize) >=
7196             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
7197                 return true;
7198
7199         return false;
7200 }
7201
7202 static int
7203 osd_dirent_reinsert(const struct lu_env *env, struct osd_device *dev,
7204                     handle_t *jh, struct dentry *dentry,
7205                     const struct lu_fid *fid, struct buffer_head *bh,
7206                     struct ldiskfs_dir_entry_2 *de, struct htree_lock *hlock,
7207                     bool dotdot)
7208 {
7209         struct inode *dir = dentry->d_parent->d_inode;
7210         struct inode *inode = dentry->d_inode;
7211         struct osd_fid_pack *rec;
7212         struct ldiskfs_dentry_param *ldp;
7213         int namelen = dentry->d_name.len;
7214         int rc;
7215         struct osd_thread_info *info = osd_oti_get(env);
7216
7217         ENTRY;
7218
7219         if (!ldiskfs_has_feature_dirdata(inode->i_sb))
7220                 RETURN(0);
7221
7222         /* There is enough space to hold the FID-in-dirent. */
7223         if (osd_dirent_has_space(de, namelen, dir->i_sb->s_blocksize, dotdot)) {
7224                 rc = osd_ldiskfs_journal_get_write_access(jh, dir->i_sb, bh,
7225                                                           LDISKFS_JTR_NONE);
7226                 if (rc != 0)
7227                         RETURN(rc);
7228
7229                 de->name[namelen] = 0;
7230                 rec = (struct osd_fid_pack *)(de->name + namelen + 1);
7231                 rec->fp_len = sizeof(struct lu_fid) + 1;
7232                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
7233                 de->file_type |= LDISKFS_DIRENT_LUFID;
7234                 rc = ldiskfs_handle_dirty_metadata(jh, NULL, bh);
7235
7236                 RETURN(rc);
7237         }
7238
7239         LASSERT(!dotdot);
7240
7241         rc = ldiskfs_delete_entry(jh, dir, de, bh);
7242         if (rc != 0)
7243                 RETURN(rc);
7244
7245         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
7246         osd_get_ldiskfs_dirent_param(ldp, fid);
7247         dentry->d_fsdata = (void *)ldp;
7248         dquot_initialize(dir);
7249         rc = osd_ldiskfs_add_entry(info, dev, jh, dentry, inode, hlock);
7250         /*
7251          * It is too bad, we cannot reinsert the name entry back.
7252          * That means we lose it!
7253          */
7254         if (rc != 0)
7255                 CDEBUG(D_LFSCK,
7256                        "%s: fail to reinsert the dirent, dir = %lu/%u, name = %.*s, "DFID": rc = %d\n",
7257                        osd_ino2name(inode), dir->i_ino, dir->i_generation,
7258                        namelen, dentry->d_name.name, PFID(fid), rc);
7259
7260         RETURN(rc);
7261 }
7262
7263 static int
7264 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
7265                         struct osd_it_ea *it, struct lu_fid *fid,
7266                         struct osd_inode_id *id, __u32 *attr)
7267 {
7268         struct osd_thread_info *info = osd_oti_get(env);
7269         struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
7270         struct osd_device *dev = osd_obj2dev(obj);
7271         struct super_block *sb = osd_sb(dev);
7272         const char *devname = osd_name(dev);
7273         struct osd_it_ea_dirent *ent = it->oie_dirent;
7274         struct inode *dir = obj->oo_inode;
7275         struct htree_lock *hlock = NULL;
7276         struct buffer_head *bh = NULL;
7277         handle_t *jh = NULL;
7278         struct ldiskfs_dir_entry_2 *de;
7279         struct dentry *dentry;
7280         struct inode *inode;
7281         const struct lu_fid *pfid = lu_object_fid(&obj->oo_dt.do_lu);
7282         int credits;
7283         int rc;
7284         bool dotdot = false;
7285         bool dirty = false;
7286         struct lu_name ln;
7287
7288         ENTRY;
7289
7290         if (ent->oied_name[0] == '.') {
7291                 if (ent->oied_namelen == 1)
7292                         RETURN(0);
7293
7294                 if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
7295                         dotdot = true;
7296         }
7297
7298         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
7299         inode = osd_iget(info, dev, id);
7300         if (IS_ERR(inode)) {
7301                 rc = PTR_ERR(inode);
7302                 if (rc == -ENOENT || rc == -ESTALE) {
7303                         /*
7304                          * Maybe dangling name entry, or
7305                          * corrupted directory entry.
7306                          */
7307                         *attr |= LUDA_UNKNOWN;
7308                         rc = 0;
7309                 } else {
7310                         CDEBUG(D_LFSCK, "%s: fail to iget() for dirent "
7311                                "check_repair, dir = %lu/%u, name = %.*s, "
7312                                "ino = %llu, rc = %d\n",
7313                                devname, dir->i_ino, dir->i_generation,
7314                                ent->oied_namelen, ent->oied_name,
7315                                ent->oied_ino, rc);
7316                 }
7317
7318                 RETURN(rc);
7319         }
7320
7321         rc = obj_name2lu_name(obj, ent->oied_name, ent->oied_namelen, &ln);
7322         if (rc)
7323                 RETURN(rc);
7324
7325         dentry = osd_child_dentry_by_inode(env, dir, ln.ln_name, ln.ln_namelen);
7326         rc = osd_get_lma(info, inode, dentry, &info->oti_ost_attrs);
7327         if (rc == -ENODATA || !fid_is_sane(&lma->lma_self_fid))
7328                 lma = NULL;
7329         else if (rc != 0)
7330                 GOTO(out, rc);
7331
7332         /*
7333          * We need to ensure that the name entry is still valid.
7334          * Because it may be removed or renamed by other already.
7335          *
7336          * The unlink or rename operation will start journal before PDO lock,
7337          * so to avoid deadlock, here we need to start journal handle before
7338          * related PDO lock also. But because we do not know whether there
7339          * will be something to be repaired before PDO lock, we just start
7340          * journal without conditions.
7341          *
7342          * We may need to remove the name entry firstly, then insert back.
7343          * One credit is for user quota file update.
7344          * One credit is for group quota file update.
7345          * Two credits are for dirty inode.
7346          */
7347         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
7348                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
7349
7350         if (dev->od_dirent_journal != 0) {
7351
7352 again:
7353                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
7354                 if (IS_ERR(jh)) {
7355                         rc = PTR_ERR(jh);
7356                         CDEBUG(D_LFSCK, "%s: fail to start trans for dirent "
7357                                "check_repair, dir = %lu/%u, credits = %d, "
7358                                "name = %.*s, ino = %llu: rc = %d\n",
7359                                devname, dir->i_ino, dir->i_generation, credits,
7360                                ent->oied_namelen, ent->oied_name,
7361                                ent->oied_ino, rc);
7362
7363                         GOTO(out_inode, rc);
7364                 }
7365
7366                 if (obj->oo_hl_head != NULL) {
7367                         hlock = osd_oti_get(env)->oti_hlock;
7368                         /*
7369                          * "0" means exclusive lock for the whole directory.
7370                          * We need to prevent others access such name entry
7371                          * during the delete + insert. Neither HLOCK_ADD nor
7372                          * HLOCK_DEL cannot guarantee the atomicity.
7373                          */
7374                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
7375                 } else {
7376                         down_write(&obj->oo_ext_idx_sem);
7377                 }
7378         } else {
7379                 if (obj->oo_hl_head != NULL) {
7380                         hlock = osd_oti_get(env)->oti_hlock;
7381                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
7382                                            LDISKFS_HLOCK_LOOKUP);
7383                 } else {
7384                         down_read(&obj->oo_ext_idx_sem);
7385                 }
7386         }
7387
7388         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
7389         if (IS_ERR(bh) || le32_to_cpu(de->inode) != inode->i_ino) {
7390                 *attr |= LUDA_IGNORE;
7391
7392                 GOTO(out, rc = 0);
7393         }
7394
7395         /*
7396          * For dotdot entry, if there is not enough space to hold the
7397          * FID-in-dirent, just keep them there. It only happens when the
7398          * device upgraded from 1.8 or restored from MDT file-level backup.
7399          * For the whole directory, only dotdot entry have no FID-in-dirent
7400          * and needs to get FID from LMA when readdir, it will not affect the
7401          * performance much.
7402          */
7403         if (dotdot && !osd_dotdot_has_space(de)) {
7404                 *attr |= LUDA_UNKNOWN;
7405
7406                 GOTO(out, rc = 0);
7407         }
7408
7409         if (lma != NULL) {
7410                 if (lu_fid_eq(fid, &lma->lma_self_fid))
7411                         GOTO(out, rc = 0);
7412
7413                 if (unlikely(lma->lma_compat & LMAC_NOT_IN_OI)) {
7414                         struct lu_fid *tfid = &lma->lma_self_fid;
7415
7416                         if (likely(dotdot &&
7417                                    fid_seq(tfid) == FID_SEQ_LOCAL_FILE &&
7418                                    fid_oid(tfid) == REMOTE_PARENT_DIR_OID)) {
7419                                 /*
7420                                  * It must be REMOTE_PARENT_DIR and as the
7421                                  * 'dotdot' entry of remote directory
7422                                  */
7423                                 *attr |= LUDA_IGNORE;
7424                         } else {
7425                                 CDEBUG(D_LFSCK, "%s: expect remote agent "
7426                                        "parent directory, but got %.*s under "
7427                                        "dir = %lu/%u with the FID "DFID"\n",
7428                                        devname, ent->oied_namelen,
7429                                        ent->oied_name, dir->i_ino,
7430                                        dir->i_generation, PFID(tfid));
7431
7432                                 *attr |= LUDA_UNKNOWN;
7433                         }
7434
7435                         GOTO(out, rc = 0);
7436                 }
7437         }
7438
7439         if (!fid_is_zero(fid)) {
7440                 rc = osd_verify_ent_by_linkea(env, inode, pfid, ent->oied_name,
7441                                               ent->oied_namelen);
7442                 if (rc == -ENOENT ||
7443                     (rc == -ENODATA &&
7444                      !(dev->od_scrub.os_scrub.os_file.sf_flags & SF_UPGRADE))) {
7445                         /*
7446                          * linkEA does not recognize the dirent entry,
7447                          * it may because the dirent entry corruption
7448                          * and points to other's inode.
7449                          */
7450                         CDEBUG(D_LFSCK, "%s: the target inode does not "
7451                                "recognize the dirent, dir = %lu/%u, "
7452                                " name = %.*s, ino = %llu, "
7453                                DFID": rc = %d\n", devname, dir->i_ino,
7454                                dir->i_generation, ent->oied_namelen,
7455                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
7456                         *attr |= LUDA_UNKNOWN;
7457
7458                         GOTO(out, rc = 0);
7459                 }
7460
7461                 if (rc && rc != -ENODATA) {
7462                         CDEBUG(D_LFSCK, "%s: fail to verify FID in the dirent, "
7463                                "dir = %lu/%u, name = %.*s, ino = %llu, "
7464                                DFID": rc = %d\n", devname, dir->i_ino,
7465                                dir->i_generation, ent->oied_namelen,
7466                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
7467                         *attr |= LUDA_UNKNOWN;
7468
7469                         GOTO(out, rc = 0);
7470                 }
7471         }
7472
7473         if (lma != NULL) {
7474                 /*
7475                  * linkEA recognizes the dirent entry, the FID-in-LMA is
7476                  * valid, trusted, in spite of fid_is_sane(fid) or not.
7477                  */
7478                 if (*attr & LUDA_VERIFY_DRYRUN) {
7479                         *fid = lma->lma_self_fid;
7480                         *attr |= LUDA_REPAIR;
7481
7482                         GOTO(out, rc = 0);
7483                 }
7484
7485                 if (jh == NULL) {
7486                         brelse(bh);
7487                         dev->od_dirent_journal = 1;
7488                         if (hlock != NULL) {
7489                                 ldiskfs_htree_unlock(hlock);
7490                                 hlock = NULL;
7491                         } else {
7492                                 up_read(&obj->oo_ext_idx_sem);
7493                         }
7494
7495                         goto again;
7496                 }
7497
7498                 *fid = lma->lma_self_fid;
7499                 dirty = true;
7500                 /* Update or append the FID-in-dirent. */
7501                 rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
7502                                          bh, de, hlock, dotdot);
7503                 if (rc == 0)
7504                         *attr |= LUDA_REPAIR;
7505                 else
7506                         CDEBUG(D_LFSCK, "%s: fail to re-insert FID after "
7507                                "the dirent, dir = %lu/%u, name = %.*s, "
7508                                "ino = %llu, "DFID": rc = %d\n",
7509                                devname, dir->i_ino, dir->i_generation,
7510                                ent->oied_namelen, ent->oied_name,
7511                                ent->oied_ino, PFID(fid), rc);
7512         } else {
7513                 /* lma is NULL, trust the FID-in-dirent if it is valid. */
7514                 if (*attr & LUDA_VERIFY_DRYRUN) {
7515                         if (fid_is_sane(fid)) {
7516                                 *attr |= LUDA_REPAIR;
7517                         } else if (dev->od_index == 0) {
7518                                 lu_igif_build(fid, inode->i_ino,
7519                                               inode->i_generation);
7520                                 *attr |= LUDA_UPGRADE;
7521                         }
7522
7523                         GOTO(out, rc = 0);
7524                 }
7525
7526                 if (jh == NULL) {
7527                         brelse(bh);
7528                         dev->od_dirent_journal = 1;
7529                         if (hlock != NULL) {
7530                                 ldiskfs_htree_unlock(hlock);
7531                                 hlock = NULL;
7532                         } else {
7533                                 up_read(&obj->oo_ext_idx_sem);
7534                         }
7535
7536                         goto again;
7537                 }
7538
7539                 dirty = true;
7540                 if (unlikely(fid_is_sane(fid))) {
7541                         /*
7542                          * FID-in-dirent exists, but FID-in-LMA is lost.
7543                          * Trust the FID-in-dirent, and add FID-in-LMA.
7544                          */
7545                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
7546                         if (rc == 0)
7547                                 *attr |= LUDA_REPAIR;
7548                         else
7549                                 CDEBUG(D_LFSCK, "%s: fail to set LMA for "
7550                                        "update dirent, dir = %lu/%u, "
7551                                        "name = %.*s, ino = %llu, "
7552                                        DFID": rc = %d\n",
7553                                        devname, dir->i_ino, dir->i_generation,
7554                                        ent->oied_namelen, ent->oied_name,
7555                                        ent->oied_ino, PFID(fid), rc);
7556                 } else if (dev->od_index == 0) {
7557                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
7558                         /*
7559                          * It is probably IGIF object. Only aappend the
7560                          * FID-in-dirent. OI scrub will process FID-in-LMA.
7561                          */
7562                         rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
7563                                                  bh, de, hlock, dotdot);
7564                         if (rc == 0)
7565                                 *attr |= LUDA_UPGRADE;
7566                         else
7567                                 CDEBUG(D_LFSCK, "%s: fail to append IGIF "
7568                                        "after the dirent, dir = %lu/%u, "
7569                                        "name = %.*s, ino = %llu, "
7570                                        DFID": rc = %d\n",
7571                                        devname, dir->i_ino, dir->i_generation,
7572                                        ent->oied_namelen, ent->oied_name,
7573                                        ent->oied_ino, PFID(fid), rc);
7574                 }
7575         }
7576
7577         GOTO(out, rc);
7578
7579 out:
7580         if (!IS_ERR(bh))
7581                 brelse(bh);
7582         if (hlock != NULL) {
7583                 ldiskfs_htree_unlock(hlock);
7584         } else {
7585                 if (dev->od_dirent_journal != 0)
7586                         up_write(&obj->oo_ext_idx_sem);
7587                 else
7588                         up_read(&obj->oo_ext_idx_sem);
7589         }
7590
7591         if (jh != NULL)
7592                 ldiskfs_journal_stop(jh);
7593
7594 out_inode:
7595         iput(inode);
7596         if (rc >= 0 && !dirty)
7597                 dev->od_dirent_journal = 0;
7598         if (ln.ln_name != ent->oied_name)
7599                 kfree(ln.ln_name);
7600
7601         return rc;
7602 }
7603
7604 /**
7605  * Returns the value at current position from iterator's in memory structure.
7606  *
7607  * \param di struct osd_it_ea, iterator's in memory structure
7608  * \param attr attr requested for dirent.
7609  * \param lde lustre dirent
7610  *
7611  * \retval   0 no error and \param lde has correct lustre dirent.
7612  * \retval -ve on error
7613  */
7614 static inline int osd_it_ea_rec(const struct lu_env *env,
7615                                 const struct dt_it *di,
7616                                 struct dt_rec *dtrec, __u32 attr)
7617 {
7618         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
7619         struct osd_object      *obj   = it->oie_obj;
7620         struct osd_device      *dev   = osd_obj2dev(obj);
7621         struct osd_thread_info *oti   = osd_oti_get(env);
7622         struct osd_inode_id    *id    = &oti->oti_id;
7623         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
7624         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
7625         __u32 ino = it->oie_dirent->oied_ino;
7626         int rc = 0;
7627
7628         ENTRY;
7629
7630         LASSERT(!is_remote_parent_ino(dev, obj->oo_inode->i_ino));
7631
7632         if (attr & LUDA_VERIFY) {
7633                 if (unlikely(is_remote_parent_ino(dev, ino))) {
7634                         attr |= LUDA_IGNORE;
7635                         /*
7636                          * If the parent is on remote MDT, and there
7637                          * is no FID-in-dirent, then we have to get
7638                          * the parent FID from the linkEA.
7639                          */
7640                         if (!fid_is_sane(fid) &&
7641                             it->oie_dirent->oied_namelen == 2 &&
7642                             it->oie_dirent->oied_name[0] == '.' &&
7643                             it->oie_dirent->oied_name[1] == '.')
7644                                 osd_get_pfid_from_linkea(env, obj, fid);
7645                 } else {
7646                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
7647                                                      &attr);
7648                 }
7649
7650                 if (!fid_is_sane(fid))
7651                         attr |= LUDA_UNKNOWN;
7652         } else {
7653                 attr &= ~LU_DIRENT_ATTRS_MASK;
7654                 if (!fid_is_sane(fid)) {
7655                         bool is_dotdot = false;
7656
7657                         if (it->oie_dirent->oied_namelen == 2 &&
7658                             it->oie_dirent->oied_name[0] == '.' &&
7659                             it->oie_dirent->oied_name[1] == '.')
7660                                 is_dotdot = true;
7661                         /*
7662                          * If the parent is on remote MDT, and there
7663                          * is no FID-in-dirent, then we have to get
7664                          * the parent FID from the linkEA.
7665                          */
7666                         if (is_remote_parent_ino(dev, ino) && is_dotdot) {
7667                                 rc = osd_get_pfid_from_linkea(env, obj, fid);
7668                         } else {
7669                                 if (is_dotdot == false &&
7670                                     OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
7671                                         RETURN(-ENOENT);
7672
7673                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
7674                         }
7675                 }
7676         }
7677
7678         /* Pack the entry anyway, at least the offset is right. */
7679         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
7680                            it->oie_dirent->oied_name,
7681                            it->oie_dirent->oied_namelen,
7682                            it->oie_dirent->oied_type, attr);
7683
7684         RETURN(rc > 0 ? 0 : rc);
7685 }
7686
7687 /**
7688  * Returns the record size size at current position.
7689  *
7690  * This function will return record(lu_dirent) size in bytes.
7691  *
7692  * \param[in] env       execution environment
7693  * \param[in] di        iterator's in memory structure
7694  * \param[in] attr      attribute of the entry, only requires LUDA_TYPE to
7695  *                      calculate the lu_dirent size.
7696  *
7697  * \retval      record size(in bytes & in memory) of the current lu_dirent
7698  *              entry.
7699  */
7700 static int osd_it_ea_rec_size(const struct lu_env *env, const struct dt_it *di,
7701                               __u32 attr)
7702 {
7703         struct osd_it_ea *it = (struct osd_it_ea *)di;
7704
7705         return lu_dirent_calc_size(it->oie_dirent->oied_namelen, attr);
7706 }
7707
7708 /**
7709  * Returns a cookie for current position of the iterator head, so that
7710  * user can use this cookie to load/start the iterator next time.
7711  *
7712  * \param di iterator's in memory structure
7713  *
7714  * \retval cookie for current position, on success
7715  */
7716 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
7717 {
7718         struct osd_it_ea *it = (struct osd_it_ea *)di;
7719
7720         return it->oie_dirent->oied_off;
7721 }
7722
7723 /**
7724  * It calls osd_ldiskfs_it_fill() which will use ->iterate*()
7725  * to load a directory entry at a time and stored it i inn,
7726  * in iterator's in-memory data structure.
7727  *
7728  * \param di struct osd_it_ea, iterator's in memory structure
7729  *
7730  * \retval +ve on success
7731  * \retval -ve on error
7732  */
7733 static int osd_it_ea_load(const struct lu_env *env,
7734                           const struct dt_it *di, __u64 hash)
7735 {
7736         struct osd_it_ea *it = (struct osd_it_ea *)di;
7737         int rc;
7738
7739         ENTRY;
7740         it->oie_file->f_pos = hash;
7741
7742         rc =  osd_ldiskfs_it_fill(env, di);
7743         if (rc > 0)
7744                 rc = -ENODATA;
7745
7746         if (rc == 0)
7747                 rc = 1;
7748
7749         RETURN(rc);
7750 }
7751
7752 /**
7753  * Index lookup function for interoperability mode (b11826).
7754  *
7755  * \param key,  key i.e. file name to be searched
7756  *
7757  * \retval +ve, on success
7758  * \retval -ve, on error
7759  */
7760 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
7761                                struct dt_rec *rec, const struct dt_key *key)
7762 {
7763         struct osd_object *obj = osd_dt_obj(dt);
7764         int rc = 0;
7765
7766         ENTRY;
7767
7768         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
7769         LINVRNT(osd_invariant(obj));
7770
7771         rc = osd_ea_lookup_rec(env, obj, rec, key);
7772         if (rc == 0)
7773                 rc = 1;
7774         RETURN(rc);
7775 }
7776
7777 /**
7778  * Index and Iterator operations for interoperability
7779  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
7780  */
7781 static const struct dt_index_operations osd_index_ea_ops = {
7782         .dio_lookup         = osd_index_ea_lookup,
7783         .dio_declare_insert = osd_index_declare_ea_insert,
7784         .dio_insert         = osd_index_ea_insert,
7785         .dio_declare_delete = osd_index_declare_ea_delete,
7786         .dio_delete         = osd_index_ea_delete,
7787         .dio_it     = {
7788                 .init     = osd_it_ea_init,
7789                 .fini     = osd_it_ea_fini,
7790                 .get      = osd_it_ea_get,
7791                 .put      = osd_it_ea_put,
7792                 .next     = osd_it_ea_next,
7793                 .key      = osd_it_ea_key,
7794                 .key_size = osd_it_ea_key_size,
7795                 .rec      = osd_it_ea_rec,
7796                 .rec_size = osd_it_ea_rec_size,
7797                 .store    = osd_it_ea_store,
7798                 .load     = osd_it_ea_load
7799         }
7800 };
7801
7802 static void *osd_key_init(const struct lu_context *ctx,
7803                           struct lu_context_key *key)
7804 {
7805         struct osd_thread_info *info;
7806
7807         OBD_ALLOC_PTR(info);
7808         if (info == NULL)
7809                 return ERR_PTR(-ENOMEM);
7810
7811         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7812         if (info->oti_it_ea_buf == NULL)
7813                 goto out_free_info;
7814
7815         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
7816
7817         info->oti_hlock = ldiskfs_htree_lock_alloc();
7818         if (info->oti_hlock == NULL)
7819                 goto out_free_ea;
7820
7821         return info;
7822
7823 out_free_ea:
7824         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7825 out_free_info:
7826         OBD_FREE_PTR(info);
7827         return ERR_PTR(-ENOMEM);
7828 }
7829
7830 static void osd_key_fini(const struct lu_context *ctx,
7831                          struct lu_context_key *key, void *data)
7832 {
7833         struct osd_thread_info *info = data;
7834         struct ldiskfs_inode_info *lli = LDISKFS_I(info->oti_inode);
7835         struct osd_idmap_cache *idc = info->oti_ins_cache;
7836
7837         if (info->oti_dio_pages) {
7838                 int i;
7839                 for (i = 0; i < PTLRPC_MAX_BRW_PAGES; i++) {
7840                         struct page *page = info->oti_dio_pages[i];
7841                         if (page) {
7842                                 LASSERT(PagePrivate2(page));
7843                                 LASSERT(PageLocked(page));
7844                                 ClearPagePrivate2(page);
7845                                 unlock_page(page);
7846                                 __free_page(page);
7847                         }
7848                 }
7849                 OBD_FREE_PTR_ARRAY_LARGE(info->oti_dio_pages,
7850                                          PTLRPC_MAX_BRW_PAGES);
7851         }
7852
7853         if (info->oti_inode != NULL)
7854                 OBD_FREE_PTR(lli);
7855         if (info->oti_hlock != NULL)
7856                 ldiskfs_htree_lock_free(info->oti_hlock);
7857         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7858         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
7859         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
7860         lu_buf_free(&info->oti_iobuf.dr_lnb_buf);
7861         lu_buf_free(&info->oti_big_buf);
7862         if (idc != NULL) {
7863                 LASSERT(info->oti_ins_cache_size > 0);
7864                 OBD_FREE_PTR_ARRAY_LARGE(idc, info->oti_ins_cache_size);
7865                 info->oti_ins_cache = NULL;
7866                 info->oti_ins_cache_size = 0;
7867         }
7868         OBD_FREE_PTR(info);
7869 }
7870
7871 static void osd_key_exit(const struct lu_context *ctx,
7872                          struct lu_context_key *key, void *data)
7873 {
7874         struct osd_thread_info *info = data;
7875
7876         LASSERT(info->oti_r_locks == 0);
7877         LASSERT(info->oti_w_locks == 0);
7878         LASSERT(info->oti_txns    == 0);
7879         LASSERTF(info->oti_dio_pages_used == 0, "%d\n",
7880                  info->oti_dio_pages_used);
7881 }
7882
7883 /* type constructor/destructor: osd_type_init, osd_type_fini */
7884 LU_TYPE_INIT_FINI(osd, &osd_key);
7885
7886 struct lu_context_key osd_key = {
7887         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
7888         .lct_init = osd_key_init,
7889         .lct_fini = osd_key_fini,
7890         .lct_exit = osd_key_exit
7891 };
7892
7893
7894 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
7895                            const char *name, struct lu_device *next)
7896 {
7897         struct osd_device *osd = osd_dev(d);
7898
7899         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname)) >=
7900             sizeof(osd->od_svname))
7901                 return -E2BIG;
7902         return osd_procfs_init(osd, name);
7903 }
7904
7905 static int osd_fid_init(const struct lu_env *env, struct osd_device *osd)
7906 {
7907         struct seq_server_site *ss = osd_seq_site(osd);
7908         int rc = 0;
7909
7910         ENTRY;
7911
7912         if (osd->od_is_ost || osd->od_cl_seq != NULL)
7913                 RETURN(0);
7914
7915         if (unlikely(ss == NULL))
7916                 RETURN(-ENODEV);
7917
7918         OBD_ALLOC_PTR(osd->od_cl_seq);
7919         if (osd->od_cl_seq == NULL)
7920                 RETURN(-ENOMEM);
7921
7922         seq_client_init(osd->od_cl_seq, NULL, LUSTRE_SEQ_METADATA,
7923                         osd->od_svname, ss->ss_server_seq);
7924
7925         if (ss->ss_node_id == 0) {
7926                 /*
7927                  * If the OSD on the sequence controller(MDT0), then allocate
7928                  * sequence here, otherwise allocate sequence after connected
7929                  * to MDT0 (see mdt_register_lwp_callback()).
7930                  */
7931                 rc = seq_server_alloc_meta(osd->od_cl_seq->lcs_srv,
7932                                    &osd->od_cl_seq->lcs_space, env);
7933         }
7934
7935         RETURN(rc);
7936 }
7937
7938 static void osd_fid_fini(const struct lu_env *env, struct osd_device *osd)
7939 {
7940         if (osd->od_cl_seq == NULL)
7941                 return;
7942
7943         seq_client_fini(osd->od_cl_seq);
7944         OBD_FREE_PTR(osd->od_cl_seq);
7945         osd->od_cl_seq = NULL;
7946 }
7947
7948 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
7949 {
7950         ENTRY;
7951
7952         /* shutdown quota slave instance associated with the device */
7953         if (o->od_quota_slave_md != NULL) {
7954                 struct qsd_instance *qsd = o->od_quota_slave_md;
7955
7956                 o->od_quota_slave_md = NULL;
7957                 qsd_fini(env, qsd);
7958         }
7959
7960         if (o->od_quota_slave_dt != NULL) {
7961                 struct qsd_instance *qsd = o->od_quota_slave_dt;
7962
7963                 o->od_quota_slave_dt = NULL;
7964                 qsd_fini(env, qsd);
7965         }
7966
7967         osd_fid_fini(env, o);
7968         osd_scrub_cleanup(env, o);
7969
7970         RETURN(0);
7971 }
7972
7973 static void osd_umount(const struct lu_env *env, struct osd_device *o)
7974 {
7975         ENTRY;
7976
7977         if (o->od_mnt != NULL) {
7978                 shrink_dcache_sb(osd_sb(o));
7979                 osd_sync(env, &o->od_dt_dev);
7980                 wait_event(o->od_commit_cb_done,
7981                           !atomic_read(&o->od_commit_cb_in_flight));
7982
7983                 mntput(o->od_mnt);
7984                 o->od_mnt = NULL;
7985         }
7986
7987         EXIT;
7988 }
7989
7990 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
7991 # ifndef LDISKFS_HAS_INCOMPAT_FEATURE
7992 /* Newer kernels provide the ldiskfs_set_feature_largedir() wrapper already,
7993  * which calls ldiskfs_update_dynamic_rev() to update ancient filesystems.
7994  * All ldiskfs filesystems are already v2, so it is a no-op and unnecessary.
7995  * This avoids maintaining patches to export this otherwise-useless function.
7996  */
7997 void ldiskfs_update_dynamic_rev(struct super_block *sb)
7998 {
7999         /* do nothing */
8000 }
8001 # endif
8002 #endif
8003
8004 static int osd_mount(const struct lu_env *env,
8005                      struct osd_device *o, struct lustre_cfg *cfg)
8006 {
8007         const char *name = lustre_cfg_string(cfg, 0);
8008         const char *dev = lustre_cfg_string(cfg, 1);
8009         const char *opts;
8010         unsigned long page, s_flags = 0, lmd_flags = 0;
8011         struct page *__page;
8012         struct file_system_type *type;
8013         char *options = NULL;
8014         const char *str;
8015         struct osd_thread_info *info = osd_oti_get(env);
8016         struct lu_fid *fid = &info->oti_fid;
8017         struct inode *inode;
8018         int rc = 0, force_over_1024tb = 0;
8019
8020         ENTRY;
8021
8022         if (o->od_mnt != NULL)
8023                 RETURN(0);
8024
8025         if (strlen(dev) >= sizeof(o->od_mntdev))
8026                 RETURN(-E2BIG);
8027         strcpy(o->od_mntdev, dev);
8028
8029         str = lustre_cfg_buf(cfg, 2);
8030         sscanf(str, "%lu:%lu", &s_flags, &lmd_flags);
8031
8032         opts = lustre_cfg_string(cfg, 3);
8033 #ifdef __BIG_ENDIAN
8034         if (opts == NULL || strstr(opts, "bigendian_extents") == NULL) {
8035                 CERROR("%s: device %s extents feature is not guaranteed to "
8036                        "work on big-endian systems. Use \"bigendian_extents\" "
8037                        "mount option to override.\n", name, dev);
8038                 RETURN(-EINVAL);
8039         }
8040 #endif
8041 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
8042         if (opts != NULL && strstr(opts, "force_over_128tb") != NULL) {
8043                 CWARN("force_over_128tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force option. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
8044         }
8045 #endif
8046 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 1, 53, 0)
8047         if (opts != NULL && strstr(opts, "force_over_256tb") != NULL) {
8048                 CWARN("force_over_256tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force options. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
8049         }
8050 #endif
8051 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
8052         if (opts != NULL && strstr(opts, "force_over_512tb") != NULL) {
8053                 CWARN("force_over_512tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force options. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
8054         }
8055 #endif
8056
8057         if (opts != NULL && strstr(opts, "force_over_1024tb") != NULL)
8058                 force_over_1024tb = 1;
8059
8060         __page = alloc_page(GFP_KERNEL);
8061         if (__page == NULL)
8062                 GOTO(out, rc = -ENOMEM);
8063         page = (unsigned long)page_address(__page);
8064         options = (char *)page;
8065         *options = '\0';
8066         if (opts != NULL) {
8067                 /* strip out the options for back compatiblity */
8068                 static const char * const sout[] = {
8069                         "mballoc",
8070                         "iopen",
8071                         "noiopen",
8072                         "iopen_nopriv",
8073                         "extents",
8074                         "noextents",
8075                         /* strip out option we processed in osd */
8076                         "bigendian_extents",
8077                         "force_over_128tb",
8078                         "force_over_256tb",
8079                         "force_over_512tb",
8080                         "force_over_1024tb",
8081                         "resetoi",
8082                         NULL
8083                 };
8084                 strncat(options, opts, PAGE_SIZE);
8085                 for (rc = 0, str = options; sout[rc]; ) {
8086                         char *op = strstr(str, sout[rc]);
8087
8088                         if (op == NULL) {
8089                                 rc++;
8090                                 str = options;
8091                                 continue;
8092                         }
8093                         if (op == options || *(op - 1) == ',') {
8094                                 str = op + strlen(sout[rc]);
8095                                 if (*str == ',' || *str == '\0') {
8096                                         *str == ',' ? str++ : str;
8097                                         memmove(op, str, strlen(str) + 1);
8098                                 }
8099                         }
8100                         for (str = op; *str != ',' && *str != '\0'; str++)
8101                                 ;
8102                 }
8103         } else {
8104                 strncat(options, "user_xattr,acl", PAGE_SIZE);
8105         }
8106
8107         /* Glom up mount options */
8108         if (*options != '\0')
8109                 strncat(options, ",", PAGE_SIZE);
8110         strncat(options, "no_mbcache,nodelalloc", PAGE_SIZE);
8111
8112         type = get_fs_type("ldiskfs");
8113         if (!type) {
8114                 CERROR("%s: cannot find ldiskfs module\n", name);
8115                 GOTO(out, rc = -ENODEV);
8116         }
8117
8118         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
8119         module_put(type->owner);
8120
8121         if (IS_ERR(o->od_mnt)) {
8122                 rc = PTR_ERR(o->od_mnt);
8123                 o->od_mnt = NULL;
8124                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
8125                 GOTO(out, rc);
8126         }
8127
8128         if (ldiskfs_blocks_count(LDISKFS_SB(osd_sb(o))->s_es) <<
8129                                  osd_sb(o)->s_blocksize_bits > 1024ULL << 40 &&
8130                                  force_over_1024tb == 0) {
8131                 CERROR("%s: device %s LDISKFS has not been tested on filesystems larger than 1024TB and may cause data corruption. Use 'force_over_1024tb' mount option to override.\n",
8132                        name, dev);
8133                 GOTO(out_mnt, rc = -EINVAL);
8134         }
8135
8136         if (lmd_flags & LMD_FLG_DEV_RDONLY) {
8137                 LCONSOLE_WARN("%s: not support dev_rdonly on this device\n",
8138                               name);
8139
8140                 GOTO(out_mnt, rc = -EOPNOTSUPP);
8141         }
8142
8143         if (!ldiskfs_has_feature_journal(o->od_mnt->mnt_sb)) {
8144                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
8145                 GOTO(out_mnt, rc = -EINVAL);
8146         }
8147
8148         if (ldiskfs_has_feature_fast_commit(o->od_mnt->mnt_sb)) {
8149                 CERROR("%s: device %s is mounted with fast_commit that breaks recovery\n",
8150                        name, dev);
8151                 GOTO(out_mnt, rc = -EOPNOTSUPP);
8152         }
8153
8154 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
8155 #ifdef LDISKFS_MOUNT_DIRDATA
8156         if (ldiskfs_has_feature_dirdata(o->od_mnt->mnt_sb))
8157                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
8158         else if (strstr(name, "MDT")) /* don't complain for MGT or OSTs */
8159                 CWARN("%s: device %s was upgraded from Lustre-1.x without "
8160                       "enabling the dirdata feature. If you do not want to "
8161                       "downgrade to Lustre-1.x again, you can enable it via "
8162                       "'tune2fs -O dirdata device'\n", name, dev);
8163 #endif
8164         /* enable large_dir on MDTs to avoid REMOTE_PARENT_DIR overflow,
8165          * and on very large OSTs to avoid object directory overflow */
8166         if (unlikely(!ldiskfs_has_feature_largedir(o->od_mnt->mnt_sb) &&
8167                      !strstr(name, "MGS"))) {
8168                 ldiskfs_set_feature_largedir(o->od_mnt->mnt_sb);
8169                 LCONSOLE_INFO("%s: enabled 'large_dir' feature on device %s\n",
8170                               name, dev);
8171         }
8172 #endif
8173         inode = osd_sb(o)->s_root->d_inode;
8174         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
8175         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
8176         if (rc != 0) {
8177                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
8178                 GOTO(out_mnt, rc);
8179         }
8180
8181         if (lmd_flags & LMD_FLG_NOSCRUB)
8182                 o->od_scrub.os_scrub.os_auto_scrub_interval = AS_NEVER;
8183
8184         if (blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev))) {
8185                 /* do not use pagecache with flash-backed storage */
8186                 o->od_writethrough_cache = 0;
8187                 o->od_read_cache = 0;
8188         }
8189
8190         GOTO(out, rc = 0);
8191
8192 out_mnt:
8193         mntput(o->od_mnt);
8194         o->od_mnt = NULL;
8195
8196 out:
8197         if (__page)
8198                 __free_page(__page);
8199
8200         return rc;
8201 }
8202
8203 static struct lu_device *osd_device_fini(const struct lu_env *env,
8204                                          struct lu_device *d)
8205 {
8206         struct osd_device *o = osd_dev(d);
8207
8208         ENTRY;
8209
8210         osd_index_backup(env, o, false);
8211         osd_shutdown(env, o);
8212         osd_procfs_fini(o);
8213         if (o->od_oi_table != NULL)
8214                 osd_oi_fini(osd_oti_get(env), o);
8215         if (o->od_extent_bytes_percpu)
8216                 free_percpu(o->od_extent_bytes_percpu);
8217         osd_obj_map_fini(o);
8218         osd_umount(env, o);
8219
8220         RETURN(NULL);
8221 }
8222
8223 static int osd_device_init0(const struct lu_env *env,
8224                             struct osd_device *o,
8225                             struct lustre_cfg *cfg)
8226 {
8227         struct lu_device *l = osd2lu_dev(o);
8228         struct osd_thread_info *info;
8229         int cplen = 0;
8230         char *opts = NULL;
8231         bool restored = false;
8232         int rc;
8233
8234         /* if the module was re-loaded, env can loose its keys */
8235         rc = lu_env_refill((struct lu_env *)env);
8236         if (rc)
8237                 GOTO(out, rc);
8238         info = osd_oti_get(env);
8239         LASSERT(info);
8240
8241         l->ld_ops = &osd_lu_ops;
8242         o->od_dt_dev.dd_ops = &osd_dt_ops;
8243
8244         spin_lock_init(&o->od_osfs_lock);
8245         mutex_init(&o->od_otable_mutex);
8246         INIT_LIST_HEAD(&o->od_orphan_list);
8247         INIT_LIST_HEAD(&o->od_index_backup_list);
8248         INIT_LIST_HEAD(&o->od_index_restore_list);
8249         spin_lock_init(&o->od_lock);
8250         o->od_index_backup_policy = LIBP_NONE;
8251         o->od_t10_type = 0;
8252         init_waitqueue_head(&o->od_commit_cb_done);
8253
8254         o->od_read_cache = 1;
8255         o->od_writethrough_cache = 1;
8256         o->od_enable_projid_xattr = 0;
8257         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
8258         o->od_readcache_max_iosize = OSD_READCACHE_MAX_IO_MB << 20;
8259         o->od_writethrough_max_iosize = OSD_WRITECACHE_MAX_IO_MB << 20;
8260         o->od_scrub.os_scrub.os_auto_scrub_interval = AS_DEFAULT;
8261         /* default fallocate to unwritten extents: LU-14326/LU-14333 */
8262         o->od_fallocate_zero_blocks = 0;
8263
8264         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
8265                         sizeof(o->od_svname));
8266         if (cplen >= sizeof(o->od_svname)) {
8267                 rc = -E2BIG;
8268                 GOTO(out, rc);
8269         }
8270
8271         o->od_index_backup_stop = 0;
8272         o->od_index = -1; /* -1 means index is invalid */
8273         rc = server_name2index(o->od_svname, &o->od_index, NULL);
8274         if (rc == LDD_F_SV_TYPE_OST)
8275                 o->od_is_ost = 1;
8276
8277         o->od_full_scrub_ratio = OFSR_DEFAULT;
8278         o->od_full_scrub_threshold_rate = FULL_SCRUB_THRESHOLD_RATE_DEFAULT;
8279         rc = osd_mount(env, o, cfg);
8280         if (rc != 0)
8281                 GOTO(out, rc);
8282
8283         /* Can only check block device after mount */
8284         o->od_nonrotational =
8285                 blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev));
8286
8287         rc = osd_obj_map_init(env, o);
8288         if (rc != 0)
8289                 GOTO(out_mnt, rc);
8290
8291         rc = lu_site_init(&o->od_site, l);
8292         if (rc != 0)
8293                 GOTO(out_compat, rc);
8294         o->od_site.ls_bottom_dev = l;
8295
8296         rc = lu_site_init_finish(&o->od_site);
8297         if (rc != 0)
8298                 GOTO(out_site, rc);
8299
8300         opts = lustre_cfg_string(cfg, 3);
8301         if (opts && strstr(opts, "resetoi"))
8302                 restored = true;
8303
8304         INIT_LIST_HEAD(&o->od_ios_list);
8305
8306         rc = lprocfs_init_brw_stats(&o->od_brw_stats);
8307         if (rc)
8308                 GOTO(out_brw_stats, rc);
8309
8310         /* setup scrub, including OI files initialization */
8311         o->od_in_init = 1;
8312         rc = osd_scrub_setup(env, o, restored);
8313         o->od_in_init = 0;
8314         if (rc < 0)
8315                 GOTO(out_brw_stats, rc);
8316
8317         rc = osd_procfs_init(o, o->od_svname);
8318         if (rc != 0) {
8319                 CERROR("%s: can't initialize procfs: rc = %d\n",
8320                        o->od_svname, rc);
8321                 GOTO(out_scrub, rc);
8322         }
8323
8324         LASSERT(l->ld_site->ls_linkage.next != NULL);
8325         LASSERT(l->ld_site->ls_linkage.prev != NULL);
8326
8327         /* initialize quota slave instance */
8328         /* currently it's no need to prepare qsd_instance_md for OST */
8329         if (!o->od_is_ost) {
8330                 o->od_quota_slave_md = qsd_init(env, o->od_svname,
8331                                                 &o->od_dt_dev, o->od_proc_entry,
8332                                                 true, true);
8333                 if (IS_ERR(o->od_quota_slave_md)) {
8334                         rc = PTR_ERR(o->od_quota_slave_md);
8335                         o->od_quota_slave_md = NULL;
8336                         GOTO(out_procfs, rc);
8337                 }
8338         }
8339
8340         o->od_quota_slave_dt = qsd_init(env, o->od_svname, &o->od_dt_dev,
8341                                         o->od_proc_entry, false, true);
8342
8343         if (IS_ERR(o->od_quota_slave_dt)) {
8344                 if (o->od_quota_slave_md != NULL) {
8345                         qsd_fini(env, o->od_quota_slave_md);
8346                         o->od_quota_slave_md = NULL;
8347                 }
8348
8349                 rc = PTR_ERR(o->od_quota_slave_dt);
8350                 o->od_quota_slave_dt = NULL;
8351                 GOTO(out_procfs, rc);
8352         }
8353
8354         o->od_extent_bytes_percpu = alloc_percpu(unsigned int);
8355         if (!o->od_extent_bytes_percpu) {
8356                 rc = -ENOMEM;
8357                 GOTO(out_procfs, rc);
8358         }
8359
8360         RETURN(0);
8361
8362 out_procfs:
8363         osd_procfs_fini(o);
8364 out_scrub:
8365         osd_scrub_cleanup(env, o);
8366 out_brw_stats:
8367         lprocfs_fini_brw_stats(&o->od_brw_stats);
8368 out_site:
8369         lu_site_fini(&o->od_site);
8370 out_compat:
8371         osd_obj_map_fini(o);
8372 out_mnt:
8373         osd_umount(env, o);
8374 out:
8375         return rc;
8376 }
8377
8378 static struct lu_device *osd_device_alloc(const struct lu_env *env,
8379                                           struct lu_device_type *t,
8380                                           struct lustre_cfg *cfg)
8381 {
8382         struct osd_device *o;
8383         int rc;
8384
8385         OBD_ALLOC_PTR(o);
8386         if (o == NULL)
8387                 return ERR_PTR(-ENOMEM);
8388
8389         rc = dt_device_init(&o->od_dt_dev, t);
8390         if (rc == 0) {
8391                 /*
8392                  * Because the ctx might be revived in dt_device_init,
8393                  * refill the env here
8394                  */
8395                 lu_env_refill((struct lu_env *)env);
8396                 rc = osd_device_init0(env, o, cfg);
8397                 if (rc)
8398                         dt_device_fini(&o->od_dt_dev);
8399         }
8400
8401         if (unlikely(rc != 0))
8402                 OBD_FREE_PTR(o);
8403
8404         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
8405 }
8406
8407 static struct lu_device *osd_device_free(const struct lu_env *env,
8408                                          struct lu_device *d)
8409 {
8410         struct osd_device *o = osd_dev(d);
8411
8412         ENTRY;
8413
8414         /* XXX: make osd top device in order to release reference */
8415         d->ld_site->ls_top_dev = d;
8416         lu_site_purge(env, d->ld_site, -1);
8417         lu_site_print(env, d->ld_site, &d->ld_site->ls_obj_hash.nelems,
8418                       D_ERROR, lu_cdebug_printer);
8419         lu_site_fini(&o->od_site);
8420         dt_device_fini(&o->od_dt_dev);
8421         OBD_FREE_PTR(o);
8422         RETURN(NULL);
8423 }
8424
8425 static int osd_process_config(const struct lu_env *env,
8426                               struct lu_device *d, struct lustre_cfg *cfg)
8427 {
8428         struct osd_device *o = osd_dev(d);
8429         ssize_t count;
8430         int rc;
8431
8432         ENTRY;
8433
8434         switch (cfg->lcfg_command) {
8435         case LCFG_SETUP:
8436                 rc = osd_mount(env, o, cfg);
8437                 break;
8438         case LCFG_CLEANUP:
8439                 /*
8440                  * For the case LCFG_PRE_CLEANUP is not called in advance,
8441                  * that may happend if hit failure during mount process.
8442                  */
8443                 osd_index_backup(env, o, false);
8444                 lu_dev_del_linkage(d->ld_site, d);
8445                 rc = osd_shutdown(env, o);
8446                 break;
8447         case LCFG_PARAM:
8448                 LASSERT(&o->od_dt_dev);
8449                 count  = class_modify_config(cfg, PARAM_OSD,
8450                                              &o->od_dt_dev.dd_kobj);
8451                 if (count < 0)
8452                         count = class_modify_config(cfg, PARAM_OST,
8453                                                     &o->od_dt_dev.dd_kobj);
8454                 rc = count > 0 ? 0 : count;
8455                 break;
8456         case LCFG_PRE_CLEANUP:
8457                 osd_scrub_stop(o);
8458                 osd_index_backup(env, o,
8459                                  o->od_index_backup_policy != LIBP_NONE);
8460                 rc = 0;
8461                 break;
8462         default:
8463                 rc = -ENOSYS;
8464         }
8465
8466         RETURN(rc);
8467 }
8468
8469 static int osd_recovery_complete(const struct lu_env *env,
8470                                  struct lu_device *d)
8471 {
8472         struct osd_device *osd = osd_dev(d);
8473         int rc = 0;
8474
8475         ENTRY;
8476
8477         if (osd->od_quota_slave_md == NULL && osd->od_quota_slave_dt == NULL)
8478                 RETURN(0);
8479
8480         /*
8481          * start qsd instance on recovery completion, this notifies the quota
8482          * slave code that we are about to process new requests now
8483          */
8484         rc = qsd_start(env, osd->od_quota_slave_dt);
8485         if (rc == 0 && osd->od_quota_slave_md != NULL)
8486                 rc = qsd_start(env, osd->od_quota_slave_md);
8487
8488         RETURN(rc);
8489 }
8490
8491 /*
8492  * we use exports to track all osd users
8493  */
8494 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
8495                            struct obd_device *obd, struct obd_uuid *cluuid,
8496                            struct obd_connect_data *data, void *localdata)
8497 {
8498         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8499         struct lustre_handle conn;
8500         int rc;
8501
8502         ENTRY;
8503
8504         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
8505
8506         rc = class_connect(&conn, obd, cluuid);
8507         if (rc)
8508                 RETURN(rc);
8509
8510         *exp = class_conn2export(&conn);
8511
8512         spin_lock(&osd->od_osfs_lock);
8513         osd->od_connects++;
8514         spin_unlock(&osd->od_osfs_lock);
8515
8516         RETURN(0);
8517 }
8518
8519 /*
8520  * once last export (we don't count self-export) disappeared
8521  * osd can be released
8522  */
8523 static int osd_obd_disconnect(struct obd_export *exp)
8524 {
8525         struct obd_device *obd = exp->exp_obd;
8526         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8527         int rc, release = 0;
8528
8529         ENTRY;
8530
8531         /* Only disconnect the underlying layers on the final disconnect. */
8532         spin_lock(&osd->od_osfs_lock);
8533         osd->od_connects--;
8534         if (osd->od_connects == 0)
8535                 release = 1;
8536         spin_unlock(&osd->od_osfs_lock);
8537
8538         rc = class_disconnect(exp); /* bz 9811 */
8539
8540         if (rc == 0 && release)
8541                 class_manual_cleanup(obd);
8542         RETURN(rc);
8543 }
8544
8545 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
8546                        struct lu_device *dev)
8547 {
8548         struct osd_device *osd = osd_dev(dev);
8549         struct lr_server_data *lsd =
8550                         &osd->od_dt_dev.dd_lu_dev.ld_site->ls_tgt->lut_lsd;
8551         int result = 0;
8552
8553         ENTRY;
8554
8555         if (osd->od_quota_slave_md != NULL) {
8556                 /* set up quota slave objects for inode */
8557                 result = qsd_prepare(env, osd->od_quota_slave_md);
8558                 if (result != 0)
8559                         RETURN(result);
8560         }
8561
8562         if (osd->od_quota_slave_dt != NULL) {
8563                 /* set up quota slave objects for block */
8564                 result = qsd_prepare(env, osd->od_quota_slave_dt);
8565                 if (result != 0)
8566                         RETURN(result);
8567         }
8568
8569
8570         if (lsd->lsd_feature_incompat & OBD_COMPAT_OST) {
8571 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 52, 0)
8572                 if (lsd->lsd_feature_rocompat & OBD_ROCOMPAT_IDX_IN_IDIF) {
8573                         osd->od_index_in_idif = 1;
8574                 } else {
8575                         osd->od_index_in_idif = 0;
8576                         result = osd_register_proc_index_in_idif(osd);
8577                         if (result != 0)
8578                                 RETURN(result);
8579                 }
8580 #else
8581                 osd->od_index_in_idif = 1;
8582 #endif
8583         }
8584
8585         result = osd_fid_init(env, osd);
8586
8587         RETURN(result);
8588 }
8589
8590 /**
8591  * Implementation of lu_device_operations::ldo_fid_alloc() for OSD
8592  *
8593  * Allocate FID.
8594  *
8595  * see include/lu_object.h for the details.
8596  */
8597 static int osd_fid_alloc(const struct lu_env *env, struct lu_device *d,
8598                          struct lu_fid *fid, struct lu_object *parent,
8599                          const struct lu_name *name)
8600 {
8601         struct osd_device *osd = osd_dev(d);
8602
8603         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
8604 }
8605
8606 static const struct lu_object_operations osd_lu_obj_ops = {
8607         .loo_object_init      = osd_object_init,
8608         .loo_object_delete    = osd_object_delete,
8609         .loo_object_release   = osd_object_release,
8610         .loo_object_free      = osd_object_free,
8611         .loo_object_print     = osd_object_print,
8612         .loo_object_invariant = osd_object_invariant
8613 };
8614
8615 const struct lu_device_operations osd_lu_ops = {
8616         .ldo_object_alloc      = osd_object_alloc,
8617         .ldo_process_config    = osd_process_config,
8618         .ldo_recovery_complete = osd_recovery_complete,
8619         .ldo_prepare           = osd_prepare,
8620         .ldo_fid_alloc         = osd_fid_alloc,
8621 };
8622
8623 static const struct lu_device_type_operations osd_device_type_ops = {
8624         .ldto_init = osd_type_init,
8625         .ldto_fini = osd_type_fini,
8626
8627         .ldto_start = osd_type_start,
8628         .ldto_stop  = osd_type_stop,
8629
8630         .ldto_device_alloc = osd_device_alloc,
8631         .ldto_device_free  = osd_device_free,
8632
8633         .ldto_device_init = osd_device_init,
8634         .ldto_device_fini = osd_device_fini
8635 };
8636
8637 static struct lu_device_type osd_device_type = {
8638         .ldt_tags     = LU_DEVICE_DT,
8639         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
8640         .ldt_ops      = &osd_device_type_ops,
8641         .ldt_ctx_tags = LCT_LOCAL,
8642 };
8643
8644 static int osd_health_check(const struct lu_env *env, struct obd_device *obd)
8645 {
8646         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8647         struct super_block *sb = osd_sb(osd);
8648
8649         return (osd->od_mnt == NULL || sb->s_flags & SB_RDONLY);
8650 }
8651
8652 /*
8653  * lprocfs legacy support.
8654  */
8655 static const struct obd_ops osd_obd_device_ops = {
8656         .o_owner = THIS_MODULE,
8657         .o_connect      = osd_obd_connect,
8658         .o_disconnect   = osd_obd_disconnect,
8659         .o_health_check = osd_health_check,
8660 };
8661
8662 static ssize_t track_declares_assert_show(struct kobject *kobj,
8663                                    struct attribute *attr,
8664                                    char *buf)
8665 {
8666         return sprintf(buf, "%d\n", ldiskfs_track_declares_assert);
8667 }
8668
8669 static ssize_t track_declares_assert_store(struct kobject *kobj,
8670                                            struct attribute *attr,
8671                                            const char *buffer, size_t count)
8672 {
8673         bool track_declares_assert;
8674         int rc;
8675
8676         rc = kstrtobool(buffer, &track_declares_assert);
8677         if (rc)
8678                 return rc;
8679
8680         ldiskfs_track_declares_assert = track_declares_assert;
8681
8682         return count;
8683 }
8684 LUSTRE_RW_ATTR(track_declares_assert);
8685
8686 static int __init osd_init(void)
8687 {
8688         struct kobject *kobj;
8689         int rc;
8690
8691         BUILD_BUG_ON(BH_DXLock >=
8692                      sizeof(((struct buffer_head *)0)->b_state) * 8);
8693 #if !defined(CONFIG_DEBUG_MUTEXES) && !defined(CONFIG_DEBUG_SPINLOCK)
8694         /* please, try to keep osd_thread_info smaller than a page */
8695         BUILD_BUG_ON(sizeof(struct osd_thread_info) > PAGE_SIZE);
8696 #endif
8697
8698         osd_oi_mod_init();
8699
8700         rc = lu_kmem_init(ldiskfs_caches);
8701         if (rc)
8702                 return rc;
8703
8704         rc = class_register_type(&osd_obd_device_ops, NULL, true,
8705                                  LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
8706         if (rc) {
8707                 lu_kmem_fini(ldiskfs_caches);
8708                 return rc;
8709         }
8710
8711         kobj = kset_find_obj(lustre_kset, LUSTRE_OSD_LDISKFS_NAME);
8712         if (kobj) {
8713                 rc = sysfs_create_file(kobj,
8714                                        &lustre_attr_track_declares_assert.attr);
8715                 kobject_put(kobj);
8716                 if (rc) {
8717                         CWARN("osd-ldiskfs: track_declares_assert failed to register with sysfs\n");
8718                         rc = 0;
8719                 }
8720         }
8721
8722         return rc;
8723 }
8724
8725 static void __exit osd_exit(void)
8726 {
8727         struct kobject *kobj;
8728
8729         kobj = kset_find_obj(lustre_kset, LUSTRE_OSD_LDISKFS_NAME);
8730         if (kobj) {
8731                 sysfs_remove_file(kobj,
8732                                   &lustre_attr_track_declares_assert.attr);
8733                 kobject_put(kobj);
8734         }
8735         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
8736         lu_kmem_fini(ldiskfs_caches);
8737 }
8738
8739 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
8740 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
8741 MODULE_VERSION(LUSTRE_VERSION_STRING);
8742 MODULE_LICENSE("GPL");
8743
8744 module_init(osd_init);
8745 module_exit(osd_exit);