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