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