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