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