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