Whamcloud - gitweb
LU-3536 osd: allocate it for each iteration.
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2014, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osd/osd_handler.c
37  *
38  * Top-level entry points into osd module
39  *
40  * Author: Nikita Danilov <nikita@clusterfs.com>
41  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
42  */
43
44 #define DEBUG_SUBSYSTEM S_OSD
45
46 #include <linux/module.h>
47
48 /* LUSTRE_VERSION_CODE */
49 #include <lustre_ver.h>
50 /* prerequisite for linux/xattr.h */
51 #include <linux/types.h>
52 /* prerequisite for linux/xattr.h */
53 #include <linux/fs.h>
54 /* XATTR_{REPLACE,CREATE} */
55 #include <linux/xattr.h>
56
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 <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 <ldiskfs/xattr.h>
76 #include <lustre_linkea.h>
77
78 int ldiskfs_pdo = 1;
79 CFS_MODULE_PARM(ldiskfs_pdo, "i", int, 0644,
80                 "ldiskfs with parallel directory operations");
81
82 int ldiskfs_track_declares_assert;
83 CFS_MODULE_PARM(ldiskfs_track_declares_assert, "i", int, 0644,
84                 "LBUG during tracking of declares");
85
86 /* Slab to allocate dynlocks */
87 struct kmem_cache *dynlock_cachep;
88
89 /* Slab to allocate osd_it_ea */
90 struct kmem_cache *osd_itea_cachep;
91
92 static struct lu_kmem_descr ldiskfs_caches[] = {
93         {
94                 .ckd_cache = &dynlock_cachep,
95                 .ckd_name  = "dynlock_cache",
96                 .ckd_size  = sizeof(struct dynlock_handle)
97         },
98         {
99                 .ckd_cache = &osd_itea_cachep,
100                 .ckd_name  = "osd_itea_cache",
101                 .ckd_size  = sizeof(struct osd_it_ea)
102         },
103         {
104                 .ckd_cache = NULL
105         }
106 };
107
108 static const char dot[] = ".";
109 static const char dotdot[] = "..";
110 static const char remote_obj_dir[] = "REM_OBJ_DIR";
111
112 static const struct lu_object_operations      osd_lu_obj_ops;
113 static const struct dt_object_operations      osd_obj_ops;
114 static const struct dt_object_operations      osd_obj_ea_ops;
115 static const struct dt_object_operations      osd_obj_otable_it_ops;
116 static const struct dt_index_operations       osd_index_iam_ops;
117 static const struct dt_index_operations       osd_index_ea_ops;
118
119 int osd_trans_declare_op2rb[] = {
120         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
121         [OSD_OT_PUNCH]          = OSD_OT_MAX,
122         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
123         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
124         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
125         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
126         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
127         [OSD_OT_WRITE]          = OSD_OT_WRITE,
128         [OSD_OT_INSERT]         = OSD_OT_DELETE,
129         [OSD_OT_DELETE]         = OSD_OT_INSERT,
130         [OSD_OT_UPDATE]         = OSD_OT_MAX,
131         [OSD_OT_QUOTA]          = OSD_OT_MAX,
132 };
133
134 static int osd_has_index(const struct osd_object *obj)
135 {
136         return obj->oo_dt.do_index_ops != NULL;
137 }
138
139 static int osd_object_invariant(const struct lu_object *l)
140 {
141         return osd_invariant(osd_obj(l));
142 }
143
144 /*
145  * Concurrency: doesn't matter
146  */
147
148 /*
149  * Concurrency: doesn't matter
150  */
151 static int osd_write_locked(const struct lu_env *env, struct osd_object *o)
152 {
153         struct osd_thread_info *oti = osd_oti_get(env);
154         return oti->oti_w_locks > 0 && o->oo_owner == env;
155 }
156
157 /*
158  * Concurrency: doesn't access mutable data
159  */
160 static int osd_root_get(const struct lu_env *env,
161                         struct dt_device *dev, struct lu_fid *f)
162 {
163         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
164         return 0;
165 }
166
167 /*
168  * OSD object methods.
169  */
170
171 /*
172  * Concurrency: no concurrent access is possible that early in object
173  * life-cycle.
174  */
175 static struct lu_object *osd_object_alloc(const struct lu_env *env,
176                                           const struct lu_object_header *hdr,
177                                           struct lu_device *d)
178 {
179         struct osd_object *mo;
180
181         OBD_ALLOC_PTR(mo);
182         if (mo != NULL) {
183                 struct lu_object *l;
184
185                 l = &mo->oo_dt.do_lu;
186                 dt_object_init(&mo->oo_dt, NULL, d);
187                 mo->oo_dt.do_ops = &osd_obj_ea_ops;
188                 l->lo_ops = &osd_lu_obj_ops;
189                 init_rwsem(&mo->oo_sem);
190                 init_rwsem(&mo->oo_ext_idx_sem);
191                 spin_lock_init(&mo->oo_guard);
192                 return l;
193         } else {
194                 return NULL;
195         }
196 }
197
198 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
199                 struct dentry *dentry, struct lustre_mdt_attrs *lma)
200 {
201         int rc;
202
203         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
204         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
205                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
206         if (rc > 0) {
207                 if ((void *)lma != (void *)info->oti_mdt_attrs_old)
208                         memcpy(lma, info->oti_mdt_attrs_old, sizeof(*lma));
209                 rc = 0;
210                 lustre_lma_swab(lma);
211                 /* Check LMA compatibility */
212                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
213                         CWARN("%.16s: unsupported incompat LMA feature(s) %#x "
214                               "for fid = "DFID", ino = %lu\n",
215                               LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
216                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
217                               PFID(&lma->lma_self_fid), inode->i_ino);
218                         rc = -EOPNOTSUPP;
219                 }
220         } else if (rc == 0) {
221                 rc = -ENODATA;
222         }
223
224         return rc;
225 }
226
227 /*
228  * retrieve object from backend ext fs.
229  **/
230 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
231                        struct osd_inode_id *id)
232 {
233         struct inode *inode = NULL;
234
235         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
236         if (IS_ERR(inode)) {
237                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
238                        id->oii_ino, PTR_ERR(inode));
239         } else if (id->oii_gen != OSD_OII_NOGEN &&
240                    inode->i_generation != id->oii_gen) {
241                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
242                        "i_generation = %u\n",
243                        id->oii_ino, id->oii_gen, inode->i_generation);
244                 iput(inode);
245                 inode = ERR_PTR(-ESTALE);
246         } else if (inode->i_nlink == 0) {
247                 /* due to parallel readdir and unlink,
248                 * we can have dead inode here. */
249                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
250                 iput(inode);
251                 inode = ERR_PTR(-ESTALE);
252         } else if (is_bad_inode(inode)) {
253                 CWARN("%.16s: bad inode: ino = %u\n",
254                 LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, id->oii_ino);
255                 iput(inode);
256                 inode = ERR_PTR(-ENOENT);
257         } else {
258                 if (id->oii_gen == OSD_OII_NOGEN)
259                         osd_id_gen(id, inode->i_ino, inode->i_generation);
260
261                 /* Do not update file c/mtime in ldiskfs.
262                  * NB: we don't have any lock to protect this because we don't
263                  * have reference on osd_object now, but contention with
264                  * another lookup + attr_set can't happen in the tiny window
265                  * between if (...) and set S_NOCMTIME. */
266                 if (!(inode->i_flags & S_NOCMTIME))
267                         inode->i_flags |= S_NOCMTIME;
268         }
269         return inode;
270 }
271
272 static struct inode *
273 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
274              struct osd_inode_id *id, struct lu_fid *fid)
275 {
276         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
277         struct inode            *inode;
278         int                      rc;
279
280         inode = osd_iget(info, dev, id);
281         if (IS_ERR(inode))
282                 return inode;
283
284         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
285         if (rc == 0) {
286                 *fid = lma->lma_self_fid;
287         } else if (rc == -ENODATA) {
288                 if (unlikely(inode == osd_sb(dev)->s_root->d_inode))
289                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
290                 else
291                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
292         } else {
293                 iput(inode);
294                 inode = ERR_PTR(rc);
295         }
296         return inode;
297 }
298
299 static struct inode *osd_iget_check(struct osd_thread_info *info,
300                                     struct osd_device *dev,
301                                     const struct lu_fid *fid,
302                                     struct osd_inode_id *id,
303                                     bool in_oi)
304 {
305         struct inode    *inode;
306         int              rc     = 0;
307         ENTRY;
308
309         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
310         if (IS_ERR(inode)) {
311                 rc = PTR_ERR(inode);
312                 if (!in_oi || (rc != -ENOENT && rc != -ESTALE)) {
313                         CDEBUG(D_INODE, "no inode: ino = %u, rc = %d\n",
314                                id->oii_ino, rc);
315
316                         GOTO(put, rc);
317                 }
318
319                 goto check_oi;
320         }
321
322         if (is_bad_inode(inode)) {
323                 rc = -ENOENT;
324                 if (!in_oi) {
325                         CDEBUG(D_INODE, "bad inode: ino = %u\n", id->oii_ino);
326
327                         GOTO(put, rc);
328                 }
329
330                 goto check_oi;
331         }
332
333         if (id->oii_gen != OSD_OII_NOGEN &&
334             inode->i_generation != id->oii_gen) {
335                 rc = -ESTALE;
336                 if (!in_oi) {
337                         CDEBUG(D_INODE, "unmatched inode: ino = %u, "
338                                "oii_gen = %u, i_generation = %u\n",
339                                id->oii_ino, id->oii_gen, inode->i_generation);
340
341                         GOTO(put, rc);
342                 }
343
344                 goto check_oi;
345         }
346
347         if (inode->i_nlink == 0) {
348                 rc = -ENOENT;
349                 if (!in_oi) {
350                         CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
351
352                         GOTO(put, rc);
353                 }
354
355                 goto check_oi;
356         }
357
358 check_oi:
359         if (rc != 0) {
360                 struct osd_inode_id saved_id = *id;
361
362                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
363
364                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
365                 /* XXX: There are some possible cases:
366                  *      1. rc = 0.
367                  *         Backup/restore caused the OI invalid.
368                  *      2. rc = 0.
369                  *         Someone unlinked the object but NOT removed
370                  *         the OI mapping, such as mount target device
371                  *         as ldiskfs, and modify something directly.
372                  *      3. rc = -ENOENT.
373                  *         Someone just removed the object between the
374                  *         former oi_lookup and the iget. It is normal.
375                  *      4. Other failure cases.
376                  *
377                  *      Generally, when the device is mounted, it will
378                  *      auto check whether the system is restored from
379                  *      file-level backup or not. We trust such detect
380                  *      to distinguish the 1st case from the 2nd case. */
381                 if (rc == 0) {
382                         if (!IS_ERR(inode) && inode->i_generation != 0 &&
383                             inode->i_generation == id->oii_gen) {
384                                 rc = -ENOENT;
385                         } else {
386                                 __u32 level = D_LFSCK;
387
388                                 rc = -EREMCHG;
389                                 if (!thread_is_running(&dev->od_scrub.os_thread))
390                                         level |= D_CONSOLE;
391
392                                 CDEBUG(level, "%s: the OI mapping for the FID "
393                                        DFID" become inconsistent, the given ID "
394                                        "%u/%u, the ID in OI mapping %u/%u\n",
395                                        osd_name(dev), PFID(fid),
396                                        saved_id.oii_ino, saved_id.oii_gen,
397                                        id->oii_ino, id->oii_ino);
398                         }
399                 }
400         } else {
401                 if (id->oii_gen == OSD_OII_NOGEN)
402                         osd_id_gen(id, inode->i_ino, inode->i_generation);
403
404                 /* Do not update file c/mtime in ldiskfs.
405                  * NB: we don't have any lock to protect this because we don't
406                  * have reference on osd_object now, but contention with
407                  * another lookup + attr_set can't happen in the tiny window
408                  * between if (...) and set S_NOCMTIME. */
409                 if (!(inode->i_flags & S_NOCMTIME))
410                         inode->i_flags |= S_NOCMTIME;
411         }
412
413         GOTO(put, rc);
414
415 put:
416         if (rc != 0) {
417                 if (!IS_ERR(inode))
418                         iput(inode);
419
420                 inode = ERR_PTR(rc);
421         }
422
423         return inode;
424 }
425
426 /**
427  * \retval +v: new filter_fid, does not contain self-fid
428  * \retval 0:  filter_fid_old, contains self-fid
429  * \retval -v: other failure cases
430  */
431 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
432                  struct dentry *dentry, struct lu_fid *fid)
433 {
434         struct filter_fid_old   *ff     = &info->oti_ff;
435         struct ost_id           *ostid  = &info->oti_ostid;
436         int                      rc;
437
438         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
439         if (rc == sizeof(*ff)) {
440                 rc = 0;
441                 ostid_set_seq(ostid, le64_to_cpu(ff->ff_seq));
442                 ostid_set_id(ostid, le64_to_cpu(ff->ff_objid));
443                 /* XXX: should use real OST index in the future. LU-3569 */
444                 ostid_to_fid(fid, ostid, 0);
445         } else if (rc == sizeof(struct filter_fid)) {
446                 rc = 1;
447         } else if (rc >= 0) {
448                 rc = -EINVAL;
449         }
450
451         return rc;
452 }
453
454 static int osd_lma_self_repair(struct osd_thread_info *info,
455                                struct osd_device *osd, struct inode *inode,
456                                const struct lu_fid *fid, __u32 compat)
457 {
458         handle_t *jh;
459         int       rc;
460
461         LASSERT(current->journal_info == NULL);
462
463         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
464                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
465         if (IS_ERR(jh)) {
466                 rc = PTR_ERR(jh);
467                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
468                       osd_name(osd), rc);
469                 return rc;
470         }
471
472         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
473         if (rc != 0)
474                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
475                       osd_name(osd), rc);
476         ldiskfs_journal_stop(jh);
477         return rc;
478 }
479
480 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
481 {
482         struct osd_thread_info  *info   = osd_oti_get(env);
483         struct osd_device       *osd    = osd_obj2dev(obj);
484         struct lustre_mdt_attrs *lma    = &info->oti_mdt_attrs;
485         struct inode            *inode  = obj->oo_inode;
486         struct dentry           *dentry = &info->oti_obj_dentry;
487         struct lu_fid           *fid    = NULL;
488         const struct lu_fid     *rfid   = lu_object_fid(&obj->oo_dt.do_lu);
489         int                      rc;
490         ENTRY;
491
492         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
493         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
494                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
495         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
496                 fid = &lma->lma_self_fid;
497                 rc = osd_get_idif(info, inode, dentry, fid);
498                 if ((rc > 0) || (rc == -ENODATA && osd->od_lma_self_repair)) {
499                         /* For the given OST-object, if it has neither LMA nor
500                          * FID in XATTR_NAME_FID, then the given FID (which is
501                          * contained in the @obj, from client RPC for locating
502                          * the OST-object) is trusted. We use it to generate
503                          * the LMA. */
504                         osd_lma_self_repair(info, osd, inode, rfid,
505                                 fid_is_on_ost(info, osd, fid, OI_CHECK_FLD) ?
506                                 LMAC_FID_ON_OST : 0);
507                         RETURN(0);
508                 }
509         }
510
511         if (unlikely(rc == -ENODATA))
512                 RETURN(0);
513
514         if (rc < 0)
515                 RETURN(rc);
516
517         if (rc > 0) {
518                 rc = 0;
519                 lustre_lma_swab(lma);
520                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
521                              CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT))) {
522                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
523                               "fid = "DFID", ino = %lu\n", osd_name(osd),
524                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
525                               PFID(rfid), inode->i_ino);
526                         rc = -EOPNOTSUPP;
527                 } else if (!(lma->lma_compat & LMAC_NOT_IN_OI)) {
528                         fid = &lma->lma_self_fid;
529                 }
530         }
531
532         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
533                 __u32 level = D_LFSCK;
534
535                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
536                         struct ost_id   *oi   = &info->oti_ostid;
537                         struct lu_fid   *fid1 = &info->oti_fid3;
538                         __u32            idx  = fid_idif_ost_idx(rfid);
539
540                         /* For old IDIF, the OST index is not part of the IDIF,
541                          * Means that different OSTs may have the same IDIFs.
542                          * Under such case, we need to make some compatible
543                          * check to make sure to trigger OI scrub properly. */
544                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
545                                 /* Given @rfid is new, LMA is old. */
546                                 fid_to_ostid(fid, oi);
547                                 ostid_to_fid(fid1, oi, idx);
548                                 if (lu_fid_eq(fid1, rfid)) {
549                                         if (osd->od_lma_self_repair)
550                                                 osd_lma_self_repair(info, osd,
551                                                         inode, rfid,
552                                                         LMAC_FID_ON_OST);
553                                         RETURN(0);
554                                 }
555                         }
556                 }
557
558
559                 rc = -EREMCHG;
560                 if (!thread_is_running(&osd->od_scrub.os_thread))
561                         level |= D_CONSOLE;
562
563                 CDEBUG(level, "%s: FID "DFID" != self_fid "DFID"\n",
564                        osd_name(osd), PFID(rfid), PFID(fid));
565         }
566
567         RETURN(rc);
568 }
569
570 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
571                           const struct lu_fid *fid,
572                           const struct lu_object_conf *conf)
573 {
574         struct osd_thread_info *info;
575         struct lu_device       *ldev   = obj->oo_dt.do_lu.lo_dev;
576         struct osd_device      *dev;
577         struct osd_idmap_cache *oic;
578         struct osd_inode_id    *id;
579         struct inode           *inode;
580         struct osd_scrub       *scrub;
581         struct scrub_file      *sf;
582         int                     result;
583         int                     saved  = 0;
584         bool                    in_oi  = false;
585         bool                    triggered = false;
586         ENTRY;
587
588         LINVRNT(osd_invariant(obj));
589         LASSERT(obj->oo_inode == NULL);
590         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID"\n", PFID(fid));
591
592         dev = osd_dev(ldev);
593         scrub = &dev->od_scrub;
594         sf = &scrub->os_file;
595         info = osd_oti_get(env);
596         LASSERT(info);
597         oic = &info->oti_cache;
598
599         if (OBD_FAIL_CHECK(OBD_FAIL_OST_ENOENT))
600                 RETURN(-ENOENT);
601
602         /* For the object is created as locking anchor, or for the object to
603          * be created on disk. No need to osd_oi_lookup() at here because FID
604          * shouldn't never be re-used, if it's really a duplicate FID from
605          * unexpected reason, we should be able to detect it later by calling
606          * do_create->osd_oi_insert(). */
607         if (conf != NULL && conf->loc_flags & LOC_F_NEW)
608                 GOTO(out, result = 0);
609
610         /* Search order: 1. per-thread cache. */
611         if (lu_fid_eq(fid, &oic->oic_fid) &&
612             likely(oic->oic_dev == dev)) {
613                 id = &oic->oic_lid;
614                 goto iget;
615         }
616
617         id = &info->oti_id;
618         if (!list_empty(&scrub->os_inconsistent_items)) {
619                 /* Search order: 2. OI scrub pending list. */
620                 result = osd_oii_lookup(dev, fid, id);
621                 if (result == 0)
622                         goto iget;
623         }
624
625         /* Search order: 3. OI files. */
626         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
627         if (result == -ENOENT) {
628                 if (!fid_is_norm(fid) ||
629                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
630                     !ldiskfs_test_bit(osd_oi_fid2idx(dev,fid),
631                                       sf->sf_oi_bitmap))
632                         GOTO(out, result = 0);
633
634                 goto trigger;
635         }
636
637         if (result != 0)
638                 GOTO(out, result);
639
640         in_oi = true;
641
642 iget:
643         inode = osd_iget_check(info, dev, fid, id, in_oi);
644         if (IS_ERR(inode)) {
645                 result = PTR_ERR(inode);
646                 if (result == -ENOENT || result == -ESTALE) {
647                         if (!in_oi)
648                                 fid_zero(&oic->oic_fid);
649
650                         GOTO(out, result = -ENOENT);
651                 } else if (result == -EREMCHG) {
652
653 trigger:
654                         if (!in_oi)
655                                 fid_zero(&oic->oic_fid);
656
657                         if (unlikely(triggered))
658                                 GOTO(out, result = saved);
659
660                         triggered = true;
661                         if (thread_is_running(&scrub->os_thread)) {
662                                 result = -EINPROGRESS;
663                         } else if (!dev->od_noscrub) {
664                                 /* Since we do not know the right OI mapping,
665                                  * we have to trigger OI scrub to scan the
666                                  * whole device. */
667                                 result = osd_scrub_start(dev, SS_AUTO_FULL |
668                                         SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT);
669                                 CDEBUG(D_LFSCK | D_CONSOLE, "%.16s: trigger OI "
670                                        "scrub by RPC for "DFID", rc = %d [1]\n",
671                                        osd_name(dev), PFID(fid),result);
672                                 if (result == 0 || result == -EALREADY)
673                                         result = -EINPROGRESS;
674                                 else
675                                         result = -EREMCHG;
676                         }
677
678                         /* We still have chance to get the valid inode: for the
679                          * object which is referenced by remote name entry, the
680                          * object on the local MDT will be linked under the dir
681                          * of "/REMOTE_PARENT_DIR" with its FID string as name.
682                          *
683                          * We do not know whether the object for the given FID
684                          * is referenced by some remote name entry or not, and
685                          * especially for DNE II, a multiple-linked object may
686                          * have many name entries reside on many MDTs.
687                          *
688                          * To simplify the operation, OSD will not distinguish
689                          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
690                          * only happened for the RPC from other MDT during the
691                          * OI scrub, or for the client side RPC with FID only,
692                          * such as FID to path, or from old connected client. */
693                         saved = result;
694                         result = osd_lookup_in_remote_parent(info, dev,
695                                                              fid, id);
696                         if (result == 0) {
697                                 in_oi = false;
698                                 goto iget;
699                         }
700
701                         result = saved;
702                 }
703
704                 GOTO(out, result);
705         }
706
707         obj->oo_inode = inode;
708         LASSERT(obj->oo_inode->i_sb == osd_sb(dev));
709
710         result = osd_check_lma(env, obj);
711         if (result != 0) {
712                 iput(inode);
713                 obj->oo_inode = NULL;
714                 if (result == -EREMCHG) {
715                         if (!in_oi) {
716                                 result = osd_oi_lookup(info, dev, fid, id,
717                                                        OI_CHECK_FLD);
718                                 if (result != 0) {
719                                         fid_zero(&oic->oic_fid);
720                                         GOTO(out, result);
721                                 }
722                         }
723
724                         goto trigger;
725                 }
726
727                 GOTO(out, result);
728         }
729
730         obj->oo_compat_dot_created = 1;
731         obj->oo_compat_dotdot_created = 1;
732
733         if (!S_ISDIR(inode->i_mode) || !ldiskfs_pdo) /* done */
734                 GOTO(out, result = 0);
735
736         LASSERT(obj->oo_hl_head == NULL);
737         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
738         if (obj->oo_hl_head == NULL) {
739                 obj->oo_inode = NULL;
740                 iput(inode);
741                 GOTO(out, result = -ENOMEM);
742         }
743         GOTO(out, result = 0);
744
745 out:
746         LINVRNT(osd_invariant(obj));
747         return result;
748 }
749
750 /*
751  * Concurrency: shouldn't matter.
752  */
753 static void osd_object_init0(struct osd_object *obj)
754 {
755         LASSERT(obj->oo_inode != NULL);
756         obj->oo_dt.do_body_ops = &osd_body_ops;
757         obj->oo_dt.do_lu.lo_header->loh_attr |=
758                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
759 }
760
761 /*
762  * Concurrency: no concurrent access is possible that early in object
763  * life-cycle.
764  */
765 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
766                            const struct lu_object_conf *conf)
767 {
768         struct osd_object *obj = osd_obj(l);
769         int result;
770
771         LINVRNT(osd_invariant(obj));
772
773         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
774                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
775                 l->lo_header->loh_attr |= LOHA_EXISTS;
776                 return 0;
777         }
778
779         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
780         obj->oo_dt.do_body_ops = &osd_body_ops_new;
781         if (result == 0 && obj->oo_inode != NULL)
782                 osd_object_init0(obj);
783
784         LINVRNT(osd_invariant(obj));
785         return result;
786 }
787
788 /*
789  * Concurrency: no concurrent access is possible that late in object
790  * life-cycle.
791  */
792 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
793 {
794         struct osd_object *obj = osd_obj(l);
795
796         LINVRNT(osd_invariant(obj));
797
798         dt_object_fini(&obj->oo_dt);
799         if (obj->oo_hl_head != NULL)
800                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
801         OBD_FREE_PTR(obj);
802 }
803
804 /*
805  * Concurrency: no concurrent access is possible that late in object
806  * life-cycle.
807  */
808 static void osd_index_fini(struct osd_object *o)
809 {
810         struct iam_container *bag;
811
812         if (o->oo_dir != NULL) {
813                 bag = &o->oo_dir->od_container;
814                 if (o->oo_inode != NULL) {
815                         if (bag->ic_object == o->oo_inode)
816                                 iam_container_fini(bag);
817                 }
818                 OBD_FREE_PTR(o->oo_dir);
819                 o->oo_dir = NULL;
820         }
821 }
822
823 /*
824  * Concurrency: no concurrent access is possible that late in object
825  * life-cycle (for all existing callers, that is. New callers have to provide
826  * their own locking.)
827  */
828 static int osd_inode_unlinked(const struct inode *inode)
829 {
830         return inode->i_nlink == 0;
831 }
832
833 enum {
834         OSD_TXN_OI_DELETE_CREDITS    = 20,
835         OSD_TXN_INODE_DELETE_CREDITS = 20
836 };
837
838 /*
839  * Journal
840  */
841
842 #if OSD_THANDLE_STATS
843 /**
844  * Set time when the handle is allocated
845  */
846 static void osd_th_alloced(struct osd_thandle *oth)
847 {
848         oth->oth_alloced = cfs_time_current();
849 }
850
851 /**
852  * Set time when the handle started
853  */
854 static void osd_th_started(struct osd_thandle *oth)
855 {
856         oth->oth_started = cfs_time_current();
857 }
858
859 /**
860  * Helper function to convert time interval to microseconds packed in
861  * long int.
862  */
863 static long interval_to_usec(cfs_time_t start, cfs_time_t end)
864 {
865         struct timeval val;
866
867         cfs_duration_usec(cfs_time_sub(end, start), &val);
868         return val.tv_sec * 1000000 + val.tv_usec;
869 }
870
871 /**
872  * Check whether the we deal with this handle for too long.
873  */
874 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
875                                 cfs_time_t alloced, cfs_time_t started,
876                                 cfs_time_t closed)
877 {
878         cfs_time_t now = cfs_time_current();
879
880         LASSERT(dev != NULL);
881
882         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
883                             interval_to_usec(alloced, started));
884         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
885                             interval_to_usec(started, closed));
886         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
887                             interval_to_usec(closed, now));
888
889         if (cfs_time_before(cfs_time_add(alloced, cfs_time_seconds(30)), now)) {
890                 CWARN("transaction handle %p was open for too long: "
891                       "now "CFS_TIME_T" ,"
892                       "alloced "CFS_TIME_T" ,"
893                       "started "CFS_TIME_T" ,"
894                       "closed "CFS_TIME_T"\n",
895                       oth, now, alloced, started, closed);
896                 libcfs_debug_dumpstack(NULL);
897         }
898 }
899
900 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
901 {                                                                       \
902         cfs_time_t __closed = cfs_time_current();                       \
903         cfs_time_t __alloced = oth->oth_alloced;                        \
904         cfs_time_t __started = oth->oth_started;                        \
905                                                                         \
906         expr;                                                           \
907         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
908 }
909
910 #else /* OSD_THANDLE_STATS */
911
912 #define osd_th_alloced(h)                  do {} while(0)
913 #define osd_th_started(h)                  do {} while(0)
914 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
915
916 #endif /* OSD_THANDLE_STATS */
917
918 /*
919  * Concurrency: doesn't access mutable data.
920  */
921 static int osd_param_is_not_sane(const struct osd_device *dev,
922                                  const struct thandle *th)
923 {
924         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
925
926         return oh->ot_credits > osd_transaction_size(dev);
927 }
928
929 /*
930  * Concurrency: shouldn't matter.
931  */
932 static void osd_trans_commit_cb(struct super_block *sb,
933                                 struct ldiskfs_journal_cb_entry *jcb, int error)
934 {
935         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
936         struct thandle     *th  = &oh->ot_super;
937         struct lu_device   *lud = &th->th_dev->dd_lu_dev;
938         struct dt_txn_commit_cb *dcb, *tmp;
939
940         LASSERT(oh->ot_handle == NULL);
941
942         if (error)
943                 CERROR("transaction @0x%p commit error: %d\n", th, error);
944
945         dt_txn_hook_commit(th);
946
947         /* call per-transaction callbacks if any */
948         list_for_each_entry_safe(dcb, tmp, &oh->ot_dcb_list, dcb_linkage) {
949                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
950                          "commit callback entry: magic=%x name='%s'\n",
951                          dcb->dcb_magic, dcb->dcb_name);
952                 list_del_init(&dcb->dcb_linkage);
953                 dcb->dcb_func(NULL, th, dcb, error);
954         }
955
956         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
957         lu_device_put(lud);
958         th->th_dev = NULL;
959
960         lu_context_exit(&th->th_ctx);
961         lu_context_fini(&th->th_ctx);
962         thandle_put(th);
963 }
964
965 static struct thandle *osd_trans_create(const struct lu_env *env,
966                                         struct dt_device *d)
967 {
968         struct osd_thread_info  *oti = osd_oti_get(env);
969         struct osd_iobuf        *iobuf = &oti->oti_iobuf;
970         struct osd_thandle      *oh;
971         struct thandle          *th;
972         ENTRY;
973
974         /* on pending IO in this thread should left from prev. request */
975         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
976
977         th = ERR_PTR(-ENOMEM);
978         OBD_ALLOC_GFP(oh, sizeof *oh, GFP_NOFS);
979         if (oh != NULL) {
980                 oh->ot_quota_trans = &oti->oti_quota_trans;
981                 memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
982                 th = &oh->ot_super;
983                 th->th_dev = d;
984                 th->th_result = 0;
985                 th->th_tags = LCT_TX_HANDLE;
986                 oh->ot_credits = 0;
987                 atomic_set(&th->th_refc, 1);
988                 th->th_alloc_size = sizeof(*oh);
989                 oti->oti_dev = osd_dt_dev(d);
990                 INIT_LIST_HEAD(&oh->ot_dcb_list);
991                 osd_th_alloced(oh);
992
993                 memset(oti->oti_declare_ops, 0,
994                                         sizeof(oti->oti_declare_ops));
995                 memset(oti->oti_declare_ops_rb, 0,
996                                         sizeof(oti->oti_declare_ops_rb));
997                 memset(oti->oti_declare_ops_cred, 0,
998                                         sizeof(oti->oti_declare_ops_cred));
999                 oti->oti_rollback = false;
1000         }
1001         RETURN(th);
1002 }
1003
1004 /*
1005  * Concurrency: shouldn't matter.
1006  */
1007 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
1008                            struct thandle *th)
1009 {
1010         struct osd_thread_info *oti = osd_oti_get(env);
1011         struct osd_device  *dev = osd_dt_dev(d);
1012         handle_t           *jh;
1013         struct osd_thandle *oh;
1014         int rc;
1015
1016         ENTRY;
1017
1018         LASSERT(current->journal_info == NULL);
1019
1020         oh = container_of0(th, struct osd_thandle, ot_super);
1021         LASSERT(oh != NULL);
1022         LASSERT(oh->ot_handle == NULL);
1023
1024         rc = dt_txn_hook_start(env, d, th);
1025         if (rc != 0)
1026                 GOTO(out, rc);
1027
1028         if (unlikely(osd_param_is_not_sane(dev, th))) {
1029                 static unsigned long last_printed;
1030                 static int last_credits;
1031
1032                 CWARN("%.16s: too many transaction credits (%d > %d)\n",
1033                       LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
1034                       oh->ot_credits,
1035                       osd_journal(dev)->j_max_transaction_buffers);
1036                 CWARN("  create: %u/%u, destroy: %u/%u\n",
1037                       oti->oti_declare_ops[OSD_OT_CREATE],
1038                       oti->oti_declare_ops_cred[OSD_OT_CREATE],
1039                       oti->oti_declare_ops[OSD_OT_DESTROY],
1040                       oti->oti_declare_ops_cred[OSD_OT_DESTROY]);
1041                 CWARN("  attr_set: %u/%u, xattr_set: %u/%u\n",
1042                       oti->oti_declare_ops[OSD_OT_ATTR_SET],
1043                       oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1044                       oti->oti_declare_ops[OSD_OT_XATTR_SET],
1045                       oti->oti_declare_ops_cred[OSD_OT_XATTR_SET]);
1046                 CWARN("  write: %u/%u, punch: %u/%u, quota %u/%u\n",
1047                       oti->oti_declare_ops[OSD_OT_WRITE],
1048                       oti->oti_declare_ops_cred[OSD_OT_WRITE],
1049                       oti->oti_declare_ops[OSD_OT_PUNCH],
1050                       oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1051                       oti->oti_declare_ops[OSD_OT_QUOTA],
1052                       oti->oti_declare_ops_cred[OSD_OT_QUOTA]);
1053                 CWARN("  insert: %u/%u, delete: %u/%u\n",
1054                       oti->oti_declare_ops[OSD_OT_INSERT],
1055                       oti->oti_declare_ops_cred[OSD_OT_INSERT],
1056                       oti->oti_declare_ops[OSD_OT_DELETE],
1057                       oti->oti_declare_ops_cred[OSD_OT_DELETE]);
1058                 CWARN("  ref_add: %u/%u, ref_del: %u/%u\n",
1059                       oti->oti_declare_ops[OSD_OT_REF_ADD],
1060                       oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1061                       oti->oti_declare_ops[OSD_OT_REF_DEL],
1062                       oti->oti_declare_ops_cred[OSD_OT_REF_DEL]);
1063
1064                 if (last_credits != oh->ot_credits &&
1065                     time_after(jiffies, last_printed +
1066                                msecs_to_jiffies(60 * MSEC_PER_SEC))) {
1067                         libcfs_debug_dumpstack(NULL);
1068                         last_credits = oh->ot_credits;
1069                         last_printed = jiffies;
1070                 }
1071                 /* XXX Limit the credits to 'max_transaction_buffers', and
1072                  *     let the underlying filesystem to catch the error if
1073                  *     we really need so many credits.
1074                  *
1075                  *     This should be removed when we can calculate the
1076                  *     credits precisely. */
1077                 oh->ot_credits = osd_transaction_size(dev);
1078         }
1079
1080         /*
1081          * XXX temporary stuff. Some abstraction layer should
1082          * be used.
1083          */
1084         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
1085         osd_th_started(oh);
1086         if (!IS_ERR(jh)) {
1087                 oh->ot_handle = jh;
1088                 LASSERT(oti->oti_txns == 0);
1089                 lu_context_init(&th->th_ctx, th->th_tags);
1090                 lu_context_enter(&th->th_ctx);
1091
1092                 lu_device_get(&d->dd_lu_dev);
1093                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
1094                               "osd-tx", th);
1095                 oti->oti_txns++;
1096                 rc = 0;
1097         } else {
1098                 rc = PTR_ERR(jh);
1099         }
1100 out:
1101         RETURN(rc);
1102 }
1103
1104 static int osd_seq_exists(const struct lu_env *env,
1105                           struct osd_device *osd, u64 seq)
1106 {
1107         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
1108         struct seq_server_site  *ss = osd_seq_site(osd);
1109         int                     rc;
1110         ENTRY;
1111
1112         LASSERT(ss != NULL);
1113         LASSERT(ss->ss_server_fld != NULL);
1114
1115         rc = osd_fld_lookup(env, osd, seq, range);
1116         if (rc != 0) {
1117                 if (rc != -ENOENT)
1118                         CERROR("%s: can't lookup FLD sequence "LPX64
1119                                ": rc = %d\n", osd_name(osd), seq, rc);
1120                 RETURN(0);
1121         }
1122
1123         RETURN(ss->ss_node_id == range->lsr_index);
1124 }
1125
1126 /*
1127  * Concurrency: shouldn't matter.
1128  */
1129 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
1130                           struct thandle *th)
1131 {
1132         int                     rc = 0;
1133         struct osd_thandle     *oh;
1134         struct osd_thread_info *oti = osd_oti_get(env);
1135         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
1136         struct qsd_instance    *qsd = oti->oti_dev->od_quota_slave;
1137         struct lquota_trans    *qtrans;
1138         ENTRY;
1139
1140         oh = container_of0(th, struct osd_thandle, ot_super);
1141
1142         qtrans = oh->ot_quota_trans;
1143         oh->ot_quota_trans = NULL;
1144
1145         if (oh->ot_handle != NULL) {
1146                 handle_t *hdl = oh->ot_handle;
1147
1148                 /*
1149                  * add commit callback
1150                  * notice we don't do this in osd_trans_start()
1151                  * as underlying transaction can change during truncate
1152                  */
1153                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
1154                                          &oh->ot_jcb);
1155
1156                 LASSERT(oti->oti_txns == 1);
1157                 oti->oti_txns--;
1158                 rc = dt_txn_hook_stop(env, th);
1159                 if (rc != 0)
1160                         CERROR("Failure in transaction hook: %d\n", rc);
1161
1162                 /* hook functions might modify th_sync */
1163                 hdl->h_sync = th->th_sync;
1164
1165                 oh->ot_handle = NULL;
1166                 OSD_CHECK_SLOW_TH(oh, oti->oti_dev,
1167                                   rc = ldiskfs_journal_stop(hdl));
1168                 if (rc != 0)
1169                         CERROR("Failure to stop transaction: %d\n", rc);
1170         } else {
1171                 thandle_put(&oh->ot_super);
1172         }
1173
1174         /* inform the quota slave device that the transaction is stopping */
1175         qsd_op_end(env, qsd, qtrans);
1176
1177         /* as we want IO to journal and data IO be concurrent, we don't block
1178          * awaiting data IO completion in osd_do_bio(), instead we wait here
1179          * once transaction is submitted to the journal. all reqular requests
1180          * don't do direct IO (except read/write), thus this wait_event becomes
1181          * no-op for them.
1182          *
1183          * IMPORTANT: we have to wait till any IO submited by the thread is
1184          * completed otherwise iobuf may be corrupted by different request
1185          */
1186         wait_event(iobuf->dr_wait,
1187                        atomic_read(&iobuf->dr_numreqs) == 0);
1188         osd_fini_iobuf(oti->oti_dev, iobuf);
1189         if (!rc)
1190                 rc = iobuf->dr_error;
1191
1192         RETURN(rc);
1193 }
1194
1195 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
1196 {
1197         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
1198                                                ot_super);
1199
1200         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
1201         LASSERT(&dcb->dcb_func != NULL);
1202         list_add(&dcb->dcb_linkage, &oh->ot_dcb_list);
1203
1204         return 0;
1205 }
1206
1207 /*
1208  * Called just before object is freed. Releases all resources except for
1209  * object itself (that is released by osd_object_free()).
1210  *
1211  * Concurrency: no concurrent access is possible that late in object
1212  * life-cycle.
1213  */
1214 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
1215 {
1216         struct osd_object *obj   = osd_obj(l);
1217         struct inode      *inode = obj->oo_inode;
1218
1219         LINVRNT(osd_invariant(obj));
1220
1221         /*
1222          * If object is unlinked remove fid->ino mapping from object index.
1223          */
1224
1225         osd_index_fini(obj);
1226         if (inode != NULL) {
1227                 struct qsd_instance     *qsd = osd_obj2dev(obj)->od_quota_slave;
1228                 qid_t                    uid = i_uid_read(inode);
1229                 qid_t                    gid = i_gid_read(inode);
1230
1231                 iput(inode);
1232                 obj->oo_inode = NULL;
1233
1234                 if (qsd != NULL) {
1235                         struct osd_thread_info  *info = osd_oti_get(env);
1236                         struct lquota_id_info   *qi = &info->oti_qi;
1237
1238                         /* Release granted quota to master if necessary */
1239                         qi->lqi_id.qid_uid = uid;
1240                         qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
1241
1242                         qi->lqi_id.qid_uid = gid;
1243                         qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
1244                 }
1245         }
1246 }
1247
1248 /*
1249  * Concurrency: ->loo_object_release() is called under site spin-lock.
1250  */
1251 static void osd_object_release(const struct lu_env *env,
1252                                struct lu_object *l)
1253 {
1254 }
1255
1256 /*
1257  * Concurrency: shouldn't matter.
1258  */
1259 static int osd_object_print(const struct lu_env *env, void *cookie,
1260                             lu_printer_t p, const struct lu_object *l)
1261 {
1262         struct osd_object *o = osd_obj(l);
1263         struct iam_descr  *d;
1264
1265         if (o->oo_dir != NULL)
1266                 d = o->oo_dir->od_container.ic_descr;
1267         else
1268                 d = NULL;
1269         return (*p)(env, cookie,
1270                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
1271                     o, o->oo_inode,
1272                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
1273                     o->oo_inode ? o->oo_inode->i_generation : 0,
1274                     d ? d->id_ops->id_name : "plain");
1275 }
1276
1277 #define GRANT_FOR_LOCAL_OIDS 32 /* 128kB for last_rcvd, quota files, ... */
1278
1279 /*
1280  * Concurrency: shouldn't matter.
1281  */
1282 int osd_statfs(const struct lu_env *env, struct dt_device *d,
1283                struct obd_statfs *sfs)
1284 {
1285         struct osd_device  *osd = osd_dt_dev(d);
1286         struct super_block *sb = osd_sb(osd);
1287         struct kstatfs     *ksfs;
1288         int result = 0;
1289
1290         if (unlikely(osd->od_mnt == NULL))
1291                 return -EINPROGRESS;
1292
1293         /* osd_lproc.c call this without env, allocate ksfs for that case */
1294         if (unlikely(env == NULL)) {
1295                 OBD_ALLOC_PTR(ksfs);
1296                 if (ksfs == NULL)
1297                         return -ENOMEM;
1298         } else {
1299                 ksfs = &osd_oti_get(env)->oti_ksfs;
1300         }
1301
1302         spin_lock(&osd->od_osfs_lock);
1303         result = sb->s_op->statfs(sb->s_root, ksfs);
1304         if (likely(result == 0)) { /* N.B. statfs can't really fail */
1305                 statfs_pack(sfs, ksfs);
1306                 if (sb->s_flags & MS_RDONLY)
1307                         sfs->os_state = OS_STATE_READONLY;
1308         }
1309
1310         spin_unlock(&osd->od_osfs_lock);
1311
1312         if (unlikely(env == NULL))
1313                 OBD_FREE_PTR(ksfs);
1314
1315         /* Reserve a small amount of space for local objects like last_rcvd,
1316          * llog, quota files, ... */
1317         if (sfs->os_bavail <= GRANT_FOR_LOCAL_OIDS) {
1318                 sfs->os_bavail = 0;
1319         } else {
1320                 sfs->os_bavail -= GRANT_FOR_LOCAL_OIDS;
1321                 /** Take out metadata overhead for indirect blocks */
1322                 sfs->os_bavail -= sfs->os_bavail >> (sb->s_blocksize_bits - 3);
1323         }
1324
1325         return result;
1326 }
1327
1328 /**
1329  * Estimate space needed for file creations. We assume the largest filename
1330  * which is 2^64 - 1, hence a filename of 20 chars.
1331  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
1332  */
1333 #ifdef __LDISKFS_DIR_REC_LEN
1334 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
1335 #else
1336 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
1337 #endif
1338
1339 /*
1340  * Concurrency: doesn't access mutable data.
1341  */
1342 static void osd_conf_get(const struct lu_env *env,
1343                          const struct dt_device *dev,
1344                          struct dt_device_param *param)
1345 {
1346         struct super_block *sb = osd_sb(osd_dt_dev(dev));
1347         int                ea_overhead;
1348
1349         /*
1350          * XXX should be taken from not-yet-existing fs abstraction layer.
1351          */
1352         param->ddp_max_name_len = LDISKFS_NAME_LEN;
1353         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
1354         param->ddp_block_shift  = sb->s_blocksize_bits;
1355         param->ddp_mount_type     = LDD_MT_LDISKFS;
1356         param->ddp_maxbytes       = sb->s_maxbytes;
1357         /* Overhead estimate should be fairly accurate, so we really take a tiny
1358          * error margin which also avoids fragmenting the filesystem too much */
1359         param->ddp_grant_reserved = 2; /* end up to be 1.9% after conversion */
1360         /* inode are statically allocated, so per-inode space consumption
1361          * is the space consumed by the directory entry */
1362         param->ddp_inodespace     = PER_OBJ_USAGE;
1363         /* per-fragment overhead to be used by the client code */
1364         param->ddp_grant_frag     = 6 * LDISKFS_BLOCK_SIZE(sb);
1365         param->ddp_mntopts      = 0;
1366         if (test_opt(sb, XATTR_USER))
1367                 param->ddp_mntopts |= MNTOPT_USERXATTR;
1368         if (test_opt(sb, POSIX_ACL))
1369                 param->ddp_mntopts |= MNTOPT_ACL;
1370
1371         /* LOD might calculate the max stripe count based on max_ea_size,
1372          * so we need take account in the overhead as well,
1373          * xattr_header + magic + xattr_entry_head */
1374         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
1375                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
1376
1377 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
1378         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EA_INODE))
1379                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
1380                                                                 ea_overhead;
1381         else
1382 #endif
1383                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
1384 }
1385
1386 /*
1387  * Concurrency: shouldn't matter.
1388  */
1389 static int osd_sync(const struct lu_env *env, struct dt_device *d)
1390 {
1391         int rc;
1392
1393         CDEBUG(D_CACHE, "syncing OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1394
1395         rc = ldiskfs_force_commit(osd_sb(osd_dt_dev(d)));
1396
1397         CDEBUG(D_CACHE, "synced OSD %s: rc = %d\n",
1398                LUSTRE_OSD_LDISKFS_NAME, rc);
1399
1400         return rc;
1401 }
1402
1403 /**
1404  * Start commit for OSD device.
1405  *
1406  * An implementation of dt_commit_async method for OSD device.
1407  * Asychronously starts underlayng fs sync and thereby a transaction
1408  * commit.
1409  *
1410  * \param env environment
1411  * \param d dt device
1412  *
1413  * \see dt_device_operations
1414  */
1415 static int osd_commit_async(const struct lu_env *env,
1416                             struct dt_device *d)
1417 {
1418         struct super_block *s = osd_sb(osd_dt_dev(d));
1419         ENTRY;
1420
1421         CDEBUG(D_HA, "async commit OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1422         RETURN(s->s_op->sync_fs(s, 0));
1423 }
1424
1425 /*
1426  * Concurrency: shouldn't matter.
1427  */
1428
1429 static int osd_ro(const struct lu_env *env, struct dt_device *d)
1430 {
1431         struct super_block *sb = osd_sb(osd_dt_dev(d));
1432         struct block_device *dev = sb->s_bdev;
1433 #ifdef HAVE_DEV_SET_RDONLY
1434         struct block_device *jdev = LDISKFS_SB(sb)->journal_bdev;
1435         int rc = 0;
1436 #else
1437         int rc = -EOPNOTSUPP;
1438 #endif
1439         ENTRY;
1440
1441 #ifdef HAVE_DEV_SET_RDONLY
1442         CERROR("*** setting %s read-only ***\n", osd_dt_dev(d)->od_svname);
1443
1444         if (jdev && (jdev != dev)) {
1445                 CDEBUG(D_IOCTL | D_HA, "set journal dev %lx rdonly\n",
1446                        (long)jdev);
1447                 dev_set_rdonly(jdev);
1448         }
1449         CDEBUG(D_IOCTL | D_HA, "set dev %lx rdonly\n", (long)dev);
1450         dev_set_rdonly(dev);
1451 #else
1452         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
1453                osd_dt_dev(d)->od_svname, (long)dev, rc);
1454 #endif
1455         RETURN(rc);
1456 }
1457
1458 /*
1459  * Concurrency: serialization provided by callers.
1460  */
1461 static int osd_init_capa_ctxt(const struct lu_env *env, struct dt_device *d,
1462                               int mode, unsigned long timeout, __u32 alg,
1463                               struct lustre_capa_key *keys)
1464 {
1465         struct osd_device *dev = osd_dt_dev(d);
1466         ENTRY;
1467
1468         dev->od_fl_capa = mode;
1469         dev->od_capa_timeout = timeout;
1470         dev->od_capa_alg = alg;
1471         dev->od_capa_keys = keys;
1472         RETURN(0);
1473 }
1474
1475 /**
1476  * Note: we do not count into QUOTA here.
1477  * If we mount with --data_journal we may need more.
1478  */
1479 const int osd_dto_credits_noquota[DTO_NR] = {
1480         /**
1481          * Insert.
1482          * INDEX_EXTRA_TRANS_BLOCKS(8) +
1483          * SINGLEDATA_TRANS_BLOCKS(8)
1484          * XXX Note: maybe iam need more, since iam have more level than
1485          *           EXT3 htree.
1486          */
1487         [DTO_INDEX_INSERT]  = 16,
1488         /**
1489          * Delete
1490          * just modify a single entry, probably merge few within a block
1491          */
1492         [DTO_INDEX_DELETE]  = 1,
1493         /**
1494          * Used for OI scrub
1495          */
1496         [DTO_INDEX_UPDATE]  = 16,
1497         /**
1498          * 4(inode, inode bits, groups, GDT)
1499          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
1500          */
1501         [DTO_OBJECT_CREATE] = 4,
1502         /**
1503          * 4(inode, inode bits, groups, GDT)
1504          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
1505          */
1506         [DTO_OBJECT_DELETE] = 4,
1507         /**
1508          * Attr set credits (inode)
1509          */
1510         [DTO_ATTR_SET_BASE] = 1,
1511         /**
1512          * Xattr set. The same as xattr of EXT3.
1513          * DATA_TRANS_BLOCKS(14)
1514          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
1515          * are also counted in. Do not know why?
1516          */
1517         [DTO_XATTR_SET]     = 14,
1518         /**
1519          * credits for inode change during write.
1520          */
1521         [DTO_WRITE_BASE]    = 3,
1522         /**
1523          * credits for single block write.
1524          */
1525         [DTO_WRITE_BLOCK]   = 14,
1526         /**
1527          * Attr set credits for chown.
1528          * This is extra credits for setattr, and it is null without quota
1529          */
1530         [DTO_ATTR_SET_CHOWN] = 0
1531 };
1532
1533 static const struct dt_device_operations osd_dt_ops = {
1534         .dt_root_get       = osd_root_get,
1535         .dt_statfs         = osd_statfs,
1536         .dt_trans_create   = osd_trans_create,
1537         .dt_trans_start    = osd_trans_start,
1538         .dt_trans_stop     = osd_trans_stop,
1539         .dt_trans_cb_add   = osd_trans_cb_add,
1540         .dt_conf_get       = osd_conf_get,
1541         .dt_sync           = osd_sync,
1542         .dt_ro             = osd_ro,
1543         .dt_commit_async   = osd_commit_async,
1544         .dt_init_capa_ctxt = osd_init_capa_ctxt,
1545 };
1546
1547 static void osd_object_read_lock(const struct lu_env *env,
1548                                  struct dt_object *dt, unsigned role)
1549 {
1550         struct osd_object *obj = osd_dt_obj(dt);
1551         struct osd_thread_info *oti = osd_oti_get(env);
1552
1553         LINVRNT(osd_invariant(obj));
1554
1555         LASSERT(obj->oo_owner != env);
1556         down_read_nested(&obj->oo_sem, role);
1557
1558         LASSERT(obj->oo_owner == NULL);
1559         oti->oti_r_locks++;
1560 }
1561
1562 static void osd_object_write_lock(const struct lu_env *env,
1563                                   struct dt_object *dt, unsigned role)
1564 {
1565         struct osd_object *obj = osd_dt_obj(dt);
1566         struct osd_thread_info *oti = osd_oti_get(env);
1567
1568         LINVRNT(osd_invariant(obj));
1569
1570         LASSERT(obj->oo_owner != env);
1571         down_write_nested(&obj->oo_sem, role);
1572
1573         LASSERT(obj->oo_owner == NULL);
1574         obj->oo_owner = env;
1575         oti->oti_w_locks++;
1576 }
1577
1578 static void osd_object_read_unlock(const struct lu_env *env,
1579                                    struct dt_object *dt)
1580 {
1581         struct osd_object *obj = osd_dt_obj(dt);
1582         struct osd_thread_info *oti = osd_oti_get(env);
1583
1584         LINVRNT(osd_invariant(obj));
1585
1586         LASSERT(oti->oti_r_locks > 0);
1587         oti->oti_r_locks--;
1588         up_read(&obj->oo_sem);
1589 }
1590
1591 static void osd_object_write_unlock(const struct lu_env *env,
1592                                     struct dt_object *dt)
1593 {
1594         struct osd_object *obj = osd_dt_obj(dt);
1595         struct osd_thread_info *oti = osd_oti_get(env);
1596
1597         LINVRNT(osd_invariant(obj));
1598
1599         LASSERT(obj->oo_owner == env);
1600         LASSERT(oti->oti_w_locks > 0);
1601         oti->oti_w_locks--;
1602         obj->oo_owner = NULL;
1603         up_write(&obj->oo_sem);
1604 }
1605
1606 static int osd_object_write_locked(const struct lu_env *env,
1607                                    struct dt_object *dt)
1608 {
1609         struct osd_object *obj = osd_dt_obj(dt);
1610
1611         LINVRNT(osd_invariant(obj));
1612
1613         return obj->oo_owner == env;
1614 }
1615
1616 static int capa_is_sane(const struct lu_env *env,
1617                         struct osd_device *dev,
1618                         struct lustre_capa *capa,
1619                         struct lustre_capa_key *keys)
1620 {
1621         struct osd_thread_info *oti = osd_oti_get(env);
1622         struct lustre_capa *tcapa = &oti->oti_capa;
1623         struct obd_capa *oc;
1624         int i, rc = 0;
1625         ENTRY;
1626
1627         oc = capa_lookup(dev->od_capa_hash, capa, 0);
1628         if (oc) {
1629                 if (capa_is_expired(oc)) {
1630                         DEBUG_CAPA(D_ERROR, capa, "expired");
1631                         rc = -ESTALE;
1632                 }
1633                 capa_put(oc);
1634                 RETURN(rc);
1635         }
1636
1637         if (capa_is_expired_sec(capa)) {
1638                 DEBUG_CAPA(D_ERROR, capa, "expired");
1639                 RETURN(-ESTALE);
1640         }
1641
1642         spin_lock(&capa_lock);
1643         for (i = 0; i < 2; i++) {
1644                 if (keys[i].lk_keyid == capa->lc_keyid) {
1645                         oti->oti_capa_key = keys[i];
1646                         break;
1647                 }
1648         }
1649         spin_unlock(&capa_lock);
1650
1651         if (i == 2) {
1652                 DEBUG_CAPA(D_ERROR, capa, "no matched capa key");
1653                 RETURN(-ESTALE);
1654         }
1655
1656         rc = capa_hmac(tcapa->lc_hmac, capa, oti->oti_capa_key.lk_key);
1657         if (rc)
1658                 RETURN(rc);
1659
1660         if (memcmp(tcapa->lc_hmac, capa->lc_hmac, sizeof(capa->lc_hmac))) {
1661                 DEBUG_CAPA(D_ERROR, capa, "HMAC mismatch");
1662                 RETURN(-EACCES);
1663         }
1664
1665         oc = capa_add(dev->od_capa_hash, capa);
1666         capa_put(oc);
1667
1668         RETURN(0);
1669 }
1670
1671 int osd_object_auth(const struct lu_env *env, struct dt_object *dt,
1672                     struct lustre_capa *capa, __u64 opc)
1673 {
1674         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
1675         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
1676         struct lu_capainfo *lci;
1677         int rc;
1678
1679         if (!osd->od_fl_capa)
1680                 return 0;
1681
1682         if (capa == BYPASS_CAPA)
1683                 return 0;
1684
1685         lci = lu_capainfo_get(env);
1686         if (unlikely(lci == NULL))
1687                 return 0;
1688
1689         if (lci->lci_auth == LC_ID_NONE)
1690                 return 0;
1691
1692         if (capa == NULL) {
1693                 CERROR("%s: no capability provided for FID "DFID": rc = %d\n",
1694                        osd_name(osd), PFID(fid), -EACCES);
1695                 return -EACCES;
1696         }
1697
1698         if (!lu_fid_eq(fid, &capa->lc_fid)) {
1699                 DEBUG_CAPA(D_ERROR, capa, "fid "DFID" mismatch with",
1700                            PFID(fid));
1701                 return -EACCES;
1702         }
1703
1704         if (!capa_opc_supported(capa, opc)) {
1705                 DEBUG_CAPA(D_ERROR, capa, "opc "LPX64" not supported by", opc);
1706                 return -EACCES;
1707         }
1708
1709         rc = capa_is_sane(env, osd, capa, osd->od_capa_keys);
1710         if (rc != 0) {
1711                 DEBUG_CAPA(D_ERROR, capa, "insane: rc = %d", rc);
1712                 return -EACCES;
1713         }
1714
1715         return 0;
1716 }
1717
1718 static struct timespec *osd_inode_time(const struct lu_env *env,
1719                                        struct inode *inode, __u64 seconds)
1720 {
1721         struct osd_thread_info  *oti = osd_oti_get(env);
1722         struct timespec         *t   = &oti->oti_time;
1723
1724         t->tv_sec = seconds;
1725         t->tv_nsec = 0;
1726         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
1727         return t;
1728 }
1729
1730
1731 static void osd_inode_getattr(const struct lu_env *env,
1732                               struct inode *inode, struct lu_attr *attr)
1733 {
1734         attr->la_valid  |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
1735                            LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
1736                            LA_FLAGS | LA_NLINK | LA_RDEV | LA_BLKSIZE |
1737                            LA_TYPE;
1738
1739         attr->la_atime   = LTIME_S(inode->i_atime);
1740         attr->la_mtime   = LTIME_S(inode->i_mtime);
1741         attr->la_ctime   = LTIME_S(inode->i_ctime);
1742         attr->la_mode    = inode->i_mode;
1743         attr->la_size    = i_size_read(inode);
1744         attr->la_blocks  = inode->i_blocks;
1745         attr->la_uid     = i_uid_read(inode);
1746         attr->la_gid     = i_gid_read(inode);
1747         attr->la_flags   = LDISKFS_I(inode)->i_flags;
1748         attr->la_nlink   = inode->i_nlink;
1749         attr->la_rdev    = inode->i_rdev;
1750         attr->la_blksize = 1 << inode->i_blkbits;
1751         attr->la_blkbits = inode->i_blkbits;
1752 }
1753
1754 static int osd_attr_get(const struct lu_env *env,
1755                         struct dt_object *dt,
1756                         struct lu_attr *attr,
1757                         struct lustre_capa *capa)
1758 {
1759         struct osd_object *obj = osd_dt_obj(dt);
1760
1761         if (!dt_object_exists(dt))
1762                 return -ENOENT;
1763
1764         LASSERT(!dt_object_remote(dt));
1765         LINVRNT(osd_invariant(obj));
1766
1767         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
1768                 return -EACCES;
1769
1770         spin_lock(&obj->oo_guard);
1771         osd_inode_getattr(env, obj->oo_inode, attr);
1772         spin_unlock(&obj->oo_guard);
1773         return 0;
1774 }
1775
1776 static int osd_declare_attr_set(const struct lu_env *env,
1777                                 struct dt_object *dt,
1778                                 const struct lu_attr *attr,
1779                                 struct thandle *handle)
1780 {
1781         struct osd_thandle     *oh;
1782         struct osd_object      *obj;
1783         struct osd_thread_info *info = osd_oti_get(env);
1784         struct lquota_id_info  *qi = &info->oti_qi;
1785         qid_t                   uid;
1786         qid_t                   gid;
1787         long long               bspace;
1788         int                     rc = 0;
1789         bool                    enforce;
1790         ENTRY;
1791
1792         LASSERT(dt != NULL);
1793         LASSERT(handle != NULL);
1794
1795         obj = osd_dt_obj(dt);
1796         LASSERT(osd_invariant(obj));
1797
1798         oh = container_of0(handle, struct osd_thandle, ot_super);
1799         LASSERT(oh->ot_handle == NULL);
1800
1801         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
1802                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
1803
1804         if (attr == NULL || obj->oo_inode == NULL)
1805                 RETURN(rc);
1806
1807         bspace   = obj->oo_inode->i_blocks;
1808         bspace <<= obj->oo_inode->i_sb->s_blocksize_bits;
1809         bspace   = toqb(bspace);
1810
1811         /* Changing ownership is always preformed by super user, it should not
1812          * fail with EDQUOT.
1813          *
1814          * We still need to call the osd_declare_qid() to calculate the journal
1815          * credits for updating quota accounting files and to trigger quota
1816          * space adjustment once the operation is completed.*/
1817         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
1818                 /* USERQUOTA */
1819                 uid = i_uid_read(obj->oo_inode);
1820                 qi->lqi_type = USRQUOTA;
1821                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
1822                 /* inode accounting */
1823                 qi->lqi_is_blk = false;
1824
1825                 /* one more inode for the new uid ... */
1826                 qi->lqi_id.qid_uid = attr->la_uid;
1827                 qi->lqi_space      = 1;
1828                 /* Reserve credits for the new uid */
1829                 rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
1830                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1831                         rc = 0;
1832                 if (rc)
1833                         RETURN(rc);
1834
1835                 /* and one less inode for the current uid */
1836                 qi->lqi_id.qid_uid = uid;
1837                 qi->lqi_space      = -1;
1838                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
1839                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1840                         rc = 0;
1841                 if (rc)
1842                         RETURN(rc);
1843
1844                 /* block accounting */
1845                 qi->lqi_is_blk = true;
1846
1847                 /* more blocks for the new uid ... */
1848                 qi->lqi_id.qid_uid = attr->la_uid;
1849                 qi->lqi_space      = bspace;
1850                 /*
1851                  * Credits for the new uid has been reserved, re-use "obj"
1852                  * to save credit reservation.
1853                  */
1854                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
1855                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1856                         rc = 0;
1857                 if (rc)
1858                         RETURN(rc);
1859
1860                 /* and finally less blocks for the current uid */
1861                 qi->lqi_id.qid_uid = uid;
1862                 qi->lqi_space      = -bspace;
1863                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
1864                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1865                         rc = 0;
1866                 if (rc)
1867                         RETURN(rc);
1868
1869                 /* GROUP QUOTA */
1870                 gid = i_gid_read(obj->oo_inode);
1871                 qi->lqi_type = GRPQUOTA;
1872                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
1873
1874                 /* inode accounting */
1875                 qi->lqi_is_blk = false;
1876
1877                 /* one more inode for the new gid ... */
1878                 qi->lqi_id.qid_gid = attr->la_gid;
1879                 qi->lqi_space      = 1;
1880                 rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
1881                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1882                         rc = 0;
1883                 if (rc)
1884                         RETURN(rc);
1885
1886                 /* and one less inode for the current gid */
1887                 qi->lqi_id.qid_gid = gid;
1888                 qi->lqi_space      = -1;
1889                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
1890                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1891                         rc = 0;
1892                 if (rc)
1893                         RETURN(rc);
1894
1895                 /* block accounting */
1896                 qi->lqi_is_blk = true;
1897
1898                 /* more blocks for the new gid ... */
1899                 qi->lqi_id.qid_gid = attr->la_gid;
1900                 qi->lqi_space      = bspace;
1901                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
1902                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1903                         rc = 0;
1904                 if (rc)
1905                         RETURN(rc);
1906
1907                 /* and finally less blocks for the current gid */
1908                 qi->lqi_id.qid_gid = gid;
1909                 qi->lqi_space      = -bspace;
1910                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
1911                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1912                         rc = 0;
1913                 if (rc)
1914                         RETURN(rc);
1915         }
1916
1917         RETURN(rc);
1918 }
1919
1920 static int osd_inode_setattr(const struct lu_env *env,
1921                              struct inode *inode, const struct lu_attr *attr)
1922 {
1923         __u64 bits = attr->la_valid;
1924
1925         /* Only allow set size for regular file */
1926         if (!S_ISREG(inode->i_mode))
1927                 bits &= ~(LA_SIZE | LA_BLOCKS);
1928
1929         if (bits == 0)
1930                 return 0;
1931
1932         if (bits & LA_ATIME)
1933                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
1934         if (bits & LA_CTIME)
1935                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
1936         if (bits & LA_MTIME)
1937                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
1938         if (bits & LA_SIZE) {
1939                 LDISKFS_I(inode)->i_disksize = attr->la_size;
1940                 i_size_write(inode, attr->la_size);
1941         }
1942
1943 #if 0
1944         /* OSD should not change "i_blocks" which is used by quota.
1945          * "i_blocks" should be changed by ldiskfs only. */
1946         if (bits & LA_BLOCKS)
1947                 inode->i_blocks = attr->la_blocks;
1948 #endif
1949         if (bits & LA_MODE)
1950                 inode->i_mode = (inode->i_mode & S_IFMT) |
1951                                 (attr->la_mode & ~S_IFMT);
1952         if (bits & LA_UID)
1953                 i_uid_write(inode, attr->la_uid);
1954         if (bits & LA_GID)
1955                 i_gid_write(inode, attr->la_gid);
1956         if (bits & LA_NLINK)
1957                 set_nlink(inode, attr->la_nlink);
1958         if (bits & LA_RDEV)
1959                 inode->i_rdev = attr->la_rdev;
1960
1961         if (bits & LA_FLAGS) {
1962                 /* always keep S_NOCMTIME */
1963                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
1964                                  S_NOCMTIME;
1965         }
1966         return 0;
1967 }
1968
1969 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
1970 {
1971         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
1972             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
1973                 struct iattr    iattr;
1974                 int             rc;
1975
1976                 ll_vfs_dq_init(inode);
1977                 iattr.ia_valid = 0;
1978                 if (attr->la_valid & LA_UID)
1979                         iattr.ia_valid |= ATTR_UID;
1980                 if (attr->la_valid & LA_GID)
1981                         iattr.ia_valid |= ATTR_GID;
1982                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
1983                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
1984
1985                 rc = ll_vfs_dq_transfer(inode, &iattr);
1986                 if (rc) {
1987                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
1988                                "enforcement enabled on the ldiskfs "
1989                                "filesystem?\n", inode->i_sb->s_id, rc);
1990                         return rc;
1991                 }
1992         }
1993         return 0;
1994 }
1995
1996 static int osd_attr_set(const struct lu_env *env,
1997                         struct dt_object *dt,
1998                         const struct lu_attr *attr,
1999                         struct thandle *handle,
2000                         struct lustre_capa *capa)
2001 {
2002         struct osd_object *obj = osd_dt_obj(dt);
2003         struct inode      *inode;
2004         int rc;
2005
2006         if (!dt_object_exists(dt))
2007                 return -ENOENT;
2008
2009         LASSERT(handle != NULL);
2010         LASSERT(!dt_object_remote(dt));
2011         LASSERT(osd_invariant(obj));
2012
2013         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2014                 return -EACCES;
2015
2016         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
2017
2018         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING)) {
2019                 struct osd_thread_info  *oti  = osd_oti_get(env);
2020                 const struct lu_fid     *fid0 = lu_object_fid(&dt->do_lu);
2021                 struct lu_fid           *fid1 = &oti->oti_fid;
2022                 struct osd_inode_id     *id   = &oti->oti_id;
2023                 struct iam_path_descr   *ipd;
2024                 struct iam_container    *bag;
2025                 struct osd_thandle      *oh;
2026                 int                      rc;
2027
2028                 fid_cpu_to_be(fid1, fid0);
2029                 memset(id, 1, sizeof(*id));
2030                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
2031                                   fid0)->oi_dir.od_container;
2032                 ipd = osd_idx_ipd_get(env, bag);
2033                 if (unlikely(ipd == NULL))
2034                         RETURN(-ENOMEM);
2035
2036                 oh = container_of0(handle, struct osd_thandle, ot_super);
2037                 rc = iam_update(oh->ot_handle, bag, (const struct iam_key *)fid1,
2038                                 (const struct iam_rec *)id, ipd);
2039                 osd_ipd_put(env, bag, ipd);
2040                 return(rc > 0 ? 0 : rc);
2041         }
2042
2043         inode = obj->oo_inode;
2044
2045         rc = osd_quota_transfer(inode, attr);
2046         if (rc)
2047                 return rc;
2048
2049         spin_lock(&obj->oo_guard);
2050         rc = osd_inode_setattr(env, inode, attr);
2051         spin_unlock(&obj->oo_guard);
2052
2053         if (!rc)
2054                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2055         return rc;
2056 }
2057
2058 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
2059                                            struct osd_object *obj,
2060                                            const char *name, const int namelen)
2061 {
2062         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
2063 }
2064
2065 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
2066                       umode_t mode, struct dt_allocation_hint *hint,
2067                       struct thandle *th)
2068 {
2069         int result;
2070         struct osd_device  *osd = osd_obj2dev(obj);
2071         struct osd_thandle *oth;
2072         struct dt_object   *parent = NULL;
2073         struct inode       *inode;
2074
2075         LINVRNT(osd_invariant(obj));
2076         LASSERT(obj->oo_inode == NULL);
2077         LASSERT(obj->oo_hl_head == NULL);
2078
2079         if (S_ISDIR(mode) && ldiskfs_pdo) {
2080                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
2081                 if (obj->oo_hl_head == NULL)
2082                         return -ENOMEM;
2083         }
2084
2085         oth = container_of(th, struct osd_thandle, ot_super);
2086         LASSERT(oth->ot_handle->h_transaction != NULL);
2087
2088         if (hint && hint->dah_parent)
2089                 parent = hint->dah_parent;
2090
2091         inode = ldiskfs_create_inode(oth->ot_handle,
2092                                      parent ? osd_dt_obj(parent)->oo_inode :
2093                                               osd_sb(osd)->s_root->d_inode,
2094                                      mode);
2095         if (!IS_ERR(inode)) {
2096                 /* Do not update file c/mtime in ldiskfs.
2097                  * NB: don't need any lock because no contention at this
2098                  * early stage */
2099                 inode->i_flags |= S_NOCMTIME;
2100
2101                 /* For new created object, it must be consistent,
2102                  * and it is unnecessary to scrub against it. */
2103                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
2104                 obj->oo_inode = inode;
2105                 result = 0;
2106         } else {
2107                 if (obj->oo_hl_head != NULL) {
2108                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
2109                         obj->oo_hl_head = NULL;
2110                 }
2111                 result = PTR_ERR(inode);
2112         }
2113         LINVRNT(osd_invariant(obj));
2114         return result;
2115 }
2116
2117 enum {
2118         OSD_NAME_LEN = 255
2119 };
2120
2121 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
2122                      struct lu_attr *attr,
2123                      struct dt_allocation_hint *hint,
2124                      struct dt_object_format *dof,
2125                      struct thandle *th)
2126 {
2127         int result;
2128         struct osd_thandle *oth;
2129         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX));
2130
2131         LASSERT(S_ISDIR(attr->la_mode));
2132
2133         oth = container_of(th, struct osd_thandle, ot_super);
2134         LASSERT(oth->ot_handle->h_transaction != NULL);
2135         result = osd_mkfile(info, obj, mode, hint, th);
2136
2137         return result;
2138 }
2139
2140 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
2141                         struct lu_attr *attr,
2142                         struct dt_allocation_hint *hint,
2143                         struct dt_object_format *dof,
2144                         struct thandle *th)
2145 {
2146         int result;
2147         struct osd_thandle *oth;
2148         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
2149
2150         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
2151
2152         LASSERT(S_ISREG(attr->la_mode));
2153
2154         oth = container_of(th, struct osd_thandle, ot_super);
2155         LASSERT(oth->ot_handle->h_transaction != NULL);
2156
2157         result = osd_mkfile(info, obj, mode, hint, th);
2158         if (result == 0) {
2159                 LASSERT(obj->oo_inode != NULL);
2160                 if (feat->dif_flags & DT_IND_VARKEY)
2161                         result = iam_lvar_create(obj->oo_inode,
2162                                                  feat->dif_keysize_max,
2163                                                  feat->dif_ptrsize,
2164                                                  feat->dif_recsize_max,
2165                                                  oth->ot_handle);
2166                 else
2167                         result = iam_lfix_create(obj->oo_inode,
2168                                                  feat->dif_keysize_max,
2169                                                  feat->dif_ptrsize,
2170                                                  feat->dif_recsize_max,
2171                                                  oth->ot_handle);
2172
2173         }
2174         return result;
2175 }
2176
2177 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
2178                      struct lu_attr *attr,
2179                      struct dt_allocation_hint *hint,
2180                      struct dt_object_format *dof,
2181                      struct thandle *th)
2182 {
2183         LASSERT(S_ISREG(attr->la_mode));
2184         return osd_mkfile(info, obj, (attr->la_mode &
2185                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2186 }
2187
2188 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
2189                      struct lu_attr *attr,
2190                      struct dt_allocation_hint *hint,
2191                      struct dt_object_format *dof,
2192                      struct thandle *th)
2193 {
2194         LASSERT(S_ISLNK(attr->la_mode));
2195         return osd_mkfile(info, obj, (attr->la_mode &
2196                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2197 }
2198
2199 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
2200                      struct lu_attr *attr,
2201                      struct dt_allocation_hint *hint,
2202                      struct dt_object_format *dof,
2203                      struct thandle *th)
2204 {
2205         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
2206         int result;
2207
2208         LINVRNT(osd_invariant(obj));
2209         LASSERT(obj->oo_inode == NULL);
2210         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
2211                 S_ISFIFO(mode) || S_ISSOCK(mode));
2212
2213         result = osd_mkfile(info, obj, mode, hint, th);
2214         if (result == 0) {
2215                 LASSERT(obj->oo_inode != NULL);
2216                 /*
2217                  * This inode should be marked dirty for i_rdev.  Currently
2218                  * that is done in the osd_attr_init().
2219                  */
2220                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
2221                                    attr->la_rdev);
2222         }
2223         LINVRNT(osd_invariant(obj));
2224         return result;
2225 }
2226
2227 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
2228                               struct lu_attr *,
2229                               struct dt_allocation_hint *hint,
2230                               struct dt_object_format *dof,
2231                               struct thandle *);
2232
2233 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
2234 {
2235         osd_obj_type_f result;
2236
2237         switch (type) {
2238         case DFT_DIR:
2239                 result = osd_mkdir;
2240                 break;
2241         case DFT_REGULAR:
2242                 result = osd_mkreg;
2243                 break;
2244         case DFT_SYM:
2245                 result = osd_mksym;
2246                 break;
2247         case DFT_NODE:
2248                 result = osd_mknod;
2249                 break;
2250         case DFT_INDEX:
2251                 result = osd_mk_index;
2252                 break;
2253
2254         default:
2255                 LBUG();
2256                 break;
2257         }
2258         return result;
2259 }
2260
2261
2262 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
2263                         struct dt_object *parent, struct dt_object *child,
2264                         umode_t child_mode)
2265 {
2266         LASSERT(ah);
2267
2268         ah->dah_parent = parent;
2269         ah->dah_mode = child_mode;
2270 }
2271
2272 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
2273                           struct lu_attr *attr, struct dt_object_format *dof)
2274 {
2275         struct inode   *inode = obj->oo_inode;
2276         __u64           valid = attr->la_valid;
2277         int             result;
2278
2279         attr->la_valid &= ~(LA_TYPE | LA_MODE);
2280
2281         if (dof->dof_type != DFT_NODE)
2282                 attr->la_valid &= ~LA_RDEV;
2283         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
2284                 attr->la_valid &= ~LA_ATIME;
2285         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
2286                 attr->la_valid &= ~LA_CTIME;
2287         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
2288                 attr->la_valid &= ~LA_MTIME;
2289
2290         result = osd_quota_transfer(inode, attr);
2291         if (result)
2292                 return;
2293
2294         if (attr->la_valid != 0) {
2295                 result = osd_inode_setattr(info->oti_env, inode, attr);
2296                 /*
2297                  * The osd_inode_setattr() should always succeed here.  The
2298                  * only error that could be returned is EDQUOT when we are
2299                  * trying to change the UID or GID of the inode. However, this
2300                  * should not happen since quota enforcement is no longer
2301                  * enabled on ldiskfs (lquota takes care of it).
2302                  */
2303                 LASSERTF(result == 0, "%d\n", result);
2304                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2305         }
2306
2307         attr->la_valid = valid;
2308 }
2309
2310 /**
2311  * Helper function for osd_object_create()
2312  *
2313  * \retval 0, on success
2314  */
2315 static int __osd_object_create(struct osd_thread_info *info,
2316                                struct osd_object *obj, struct lu_attr *attr,
2317                                struct dt_allocation_hint *hint,
2318                                struct dt_object_format *dof,
2319                                struct thandle *th)
2320 {
2321         int     result;
2322         __u32   umask;
2323
2324         /* we drop umask so that permissions we pass are not affected */
2325         umask = current->fs->umask;
2326         current->fs->umask = 0;
2327
2328         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
2329                                                   th);
2330         if (result == 0) {
2331                 osd_attr_init(info, obj, attr, dof);
2332                 osd_object_init0(obj);
2333                 /* bz 24037 */
2334                 if (obj->oo_inode && (obj->oo_inode->i_state & I_NEW))
2335                         unlock_new_inode(obj->oo_inode);
2336         }
2337
2338         /* restore previous umask value */
2339         current->fs->umask = umask;
2340
2341         return result;
2342 }
2343
2344 /**
2345  * Helper function for osd_object_create()
2346  *
2347  * \retval 0, on success
2348  */
2349 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
2350                            const struct lu_fid *fid, struct thandle *th)
2351 {
2352         struct osd_thread_info *info = osd_oti_get(env);
2353         struct osd_inode_id    *id   = &info->oti_id;
2354         struct osd_device      *osd  = osd_obj2dev(obj);
2355         struct osd_thandle     *oh;
2356
2357         LASSERT(obj->oo_inode != NULL);
2358
2359         oh = container_of0(th, struct osd_thandle, ot_super);
2360         LASSERT(oh->ot_handle);
2361
2362         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
2363         return osd_oi_insert(info, osd, fid, id, oh->ot_handle, OI_CHECK_FLD);
2364 }
2365
2366 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
2367                    u64 seq, struct lu_seq_range *range)
2368 {
2369         struct seq_server_site  *ss = osd_seq_site(osd);
2370
2371         if (fid_seq_is_idif(seq)) {
2372                 fld_range_set_ost(range);
2373                 range->lsr_index = idif_ost_idx(seq);
2374                 return 0;
2375         }
2376
2377         if (!fid_seq_in_fldb(seq)) {
2378                 fld_range_set_mdt(range);
2379                 if (ss != NULL)
2380                         /* FIXME: If ss is NULL, it suppose not get lsr_index
2381                          * at all */
2382                         range->lsr_index = ss->ss_node_id;
2383                 return 0;
2384         }
2385
2386         LASSERT(ss != NULL);
2387         fld_range_set_any(range);
2388         /* OSD will only do local fld lookup */
2389         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
2390 }
2391
2392 /*
2393  * Concurrency: no external locking is necessary.
2394  */
2395 static int osd_declare_object_create(const struct lu_env *env,
2396                                      struct dt_object *dt,
2397                                      struct lu_attr *attr,
2398                                      struct dt_allocation_hint *hint,
2399                                      struct dt_object_format *dof,
2400                                      struct thandle *handle)
2401 {
2402         struct osd_thandle      *oh;
2403         int                      rc;
2404         ENTRY;
2405
2406         LASSERT(handle != NULL);
2407
2408         oh = container_of0(handle, struct osd_thandle, ot_super);
2409         LASSERT(oh->ot_handle == NULL);
2410
2411         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
2412                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
2413         /* Reuse idle OI block may cause additional one OI block
2414          * to be changed. */
2415         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2416                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
2417
2418         /* If this is directory, then we expect . and .. to be inserted as
2419          * well. The one directory block always needs to be created for the
2420          * directory, so we could use DTO_WRITE_BASE here (GDT, block bitmap,
2421          * block), there is no danger of needing a tree for the first block.
2422          */
2423         if (attr && S_ISDIR(attr->la_mode)) {
2424                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2425                                      osd_dto_credits_noquota[DTO_WRITE_BASE]);
2426                 osd_trans_declare_op(env, oh, OSD_OT_INSERT, 0);
2427         }
2428
2429         if (!attr)
2430                 RETURN(0);
2431
2432         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid, 1, oh,
2433                                    osd_dt_obj(dt), false, NULL, false);
2434         if (rc != 0)
2435                 RETURN(rc);
2436
2437         RETURN(rc);
2438 }
2439
2440 static int osd_object_create(const struct lu_env *env, struct dt_object *dt,
2441                              struct lu_attr *attr,
2442                              struct dt_allocation_hint *hint,
2443                              struct dt_object_format *dof, struct thandle *th)
2444 {
2445         const struct lu_fid     *fid    = lu_object_fid(&dt->do_lu);
2446         struct osd_object       *obj    = osd_dt_obj(dt);
2447         struct osd_thread_info  *info   = osd_oti_get(env);
2448         int result;
2449         ENTRY;
2450
2451         if (dt_object_exists(dt))
2452                 return -EEXIST;
2453
2454         LINVRNT(osd_invariant(obj));
2455         LASSERT(!dt_object_remote(dt));
2456         LASSERT(osd_write_locked(env, obj));
2457         LASSERT(th != NULL);
2458
2459         if (unlikely(fid_is_acct(fid)))
2460                 /* Quota files can't be created from the kernel any more,
2461                  * 'tune2fs -O quota' will take care of creating them */
2462                 RETURN(-EPERM);
2463
2464         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2465         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2466
2467         result = __osd_object_create(info, obj, attr, hint, dof, th);
2468         if (result == 0)
2469                 result = __osd_oi_insert(env, obj, fid, th);
2470
2471         LASSERT(ergo(result == 0,
2472                      dt_object_exists(dt) && !dt_object_remote(dt)));
2473
2474         LASSERT(osd_invariant(obj));
2475         RETURN(result);
2476 }
2477
2478 /**
2479  * Called to destroy on-disk representation of the object
2480  *
2481  * Concurrency: must be locked
2482  */
2483 static int osd_declare_object_destroy(const struct lu_env *env,
2484                                       struct dt_object *dt,
2485                                       struct thandle *th)
2486 {
2487         struct osd_object  *obj = osd_dt_obj(dt);
2488         struct inode       *inode = obj->oo_inode;
2489         struct osd_thandle *oh;
2490         int                 rc;
2491         ENTRY;
2492
2493         oh = container_of0(th, struct osd_thandle, ot_super);
2494         LASSERT(oh->ot_handle == NULL);
2495         LASSERT(inode);
2496
2497         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
2498                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
2499         /* Recycle idle OI leaf may cause additional three OI blocks
2500          * to be changed. */
2501         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
2502                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
2503         /* one less inode */
2504         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
2505                                    -1, oh, obj, false, NULL, false);
2506         if (rc)
2507                 RETURN(rc);
2508         /* data to be truncated */
2509         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
2510                                    0, oh, obj, true, NULL, false);
2511         RETURN(rc);
2512 }
2513
2514 static int osd_object_destroy(const struct lu_env *env,
2515                               struct dt_object *dt,
2516                               struct thandle *th)
2517 {
2518         const struct lu_fid    *fid = lu_object_fid(&dt->do_lu);
2519         struct osd_object      *obj = osd_dt_obj(dt);
2520         struct inode           *inode = obj->oo_inode;
2521         struct osd_device      *osd = osd_obj2dev(obj);
2522         struct osd_thandle     *oh;
2523         int                     result;
2524         ENTRY;
2525
2526         oh = container_of0(th, struct osd_thandle, ot_super);
2527         LASSERT(oh->ot_handle);
2528         LASSERT(inode);
2529         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
2530
2531         if (unlikely(fid_is_acct(fid)))
2532                 RETURN(-EPERM);
2533
2534         if (S_ISDIR(inode->i_mode)) {
2535                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1 ||
2536                         inode->i_nlink == 2);
2537                 /* it will check/delete the inode from remote parent,
2538                  * how to optimize it? unlink performance impaction XXX */
2539                 result = osd_delete_from_remote_parent(env, osd, obj, oh);
2540                 if (result != 0 && result != -ENOENT) {
2541                         CERROR("%s: delete inode "DFID": rc = %d\n",
2542                                osd_name(osd), PFID(fid), result);
2543                 }
2544                 spin_lock(&obj->oo_guard);
2545                 clear_nlink(inode);
2546                 spin_unlock(&obj->oo_guard);
2547                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2548         }
2549
2550         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
2551
2552         result = osd_oi_delete(osd_oti_get(env), osd, fid, oh->ot_handle,
2553                                OI_CHECK_FLD);
2554
2555         /* XXX: add to ext3 orphan list */
2556         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
2557
2558         /* not needed in the cache anymore */
2559         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
2560
2561         RETURN(0);
2562 }
2563
2564 /**
2565  * Put the fid into lustre_mdt_attrs, and then place the structure
2566  * inode's ea. This fid should not be altered during the life time
2567  * of the inode.
2568  *
2569  * \retval +ve, on success
2570  * \retval -ve, on error
2571  *
2572  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
2573  */
2574 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
2575                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
2576 {
2577         struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
2578         int                      rc;
2579         ENTRY;
2580
2581         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
2582                 RETURN(0);
2583
2584         lustre_lma_init(lma, fid, compat, incompat);
2585         lustre_lma_swab(lma);
2586
2587         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma, sizeof(*lma),
2588                              XATTR_CREATE);
2589         /* LMA may already exist, but we need to check that all the
2590          * desired compat/incompat flags have been added. */
2591         if (unlikely(rc == -EEXIST)) {
2592                 if (compat == 0 && incompat == 0)
2593                         RETURN(0);
2594
2595                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
2596                                      XATTR_NAME_LMA, info->oti_mdt_attrs_old,
2597                                      LMA_OLD_SIZE);
2598                 if (rc <= 0)
2599                         RETURN(-EINVAL);
2600
2601                 lustre_lma_swab(lma);
2602                 if (!(~lma->lma_compat & compat) &&
2603                     !(~lma->lma_incompat & incompat))
2604                         RETURN(0);
2605
2606                 lma->lma_compat |= compat;
2607                 lma->lma_incompat |= incompat;
2608                 lustre_lma_swab(lma);
2609                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
2610                                      sizeof(*lma), XATTR_REPLACE);
2611         }
2612
2613         RETURN(rc);
2614 }
2615
2616 /**
2617  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
2618  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
2619  * To have compatilibility with 1.8 ldiskfs driver we need to have
2620  * magic number at start of fid data.
2621  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
2622  * its inmemory API.
2623  */
2624 static void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
2625                                          const struct lu_fid *fid)
2626 {
2627         if (!fid_is_namespace_visible(fid) ||
2628             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
2629                 param->edp_magic = 0;
2630                 return;
2631         }
2632
2633         param->edp_magic = LDISKFS_LUFID_MAGIC;
2634         param->edp_len =  sizeof(struct lu_fid) + 1;
2635         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
2636 }
2637
2638 /**
2639  * Try to read the fid from inode ea into dt_rec.
2640  *
2641  * \param fid object fid.
2642  *
2643  * \retval 0 on success
2644  */
2645 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
2646                           __u32 ino, struct lu_fid *fid,
2647                           struct osd_inode_id *id)
2648 {
2649         struct osd_thread_info *info  = osd_oti_get(env);
2650         struct inode           *inode;
2651         ENTRY;
2652
2653         osd_id_gen(id, ino, OSD_OII_NOGEN);
2654         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
2655         if (IS_ERR(inode))
2656                 RETURN(PTR_ERR(inode));
2657
2658         iput(inode);
2659         RETURN(0);
2660 }
2661
2662 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
2663                                         struct inode *dir,
2664                                         struct inode *parent_dir,
2665                                         const struct lu_fid *dot_fid,
2666                                         const struct lu_fid *dot_dot_fid,
2667                                         struct osd_thandle *oth)
2668 {
2669         struct ldiskfs_dentry_param *dot_ldp;
2670         struct ldiskfs_dentry_param *dot_dot_ldp;
2671
2672         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
2673         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
2674
2675         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
2676         dot_ldp->edp_magic = 0;
2677         return ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
2678                                         dir, dot_ldp, dot_dot_ldp);
2679 }
2680
2681 /**
2682  * Create an local agent inode for remote entry
2683  */
2684 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
2685                                                   struct osd_device *osd,
2686                                                   struct osd_object *pobj,
2687                                                   const struct lu_fid *fid,
2688                                                   __u32 type,
2689                                                   struct thandle *th)
2690 {
2691         struct osd_thread_info  *info = osd_oti_get(env);
2692         struct inode            *local;
2693         struct osd_thandle      *oh;
2694         int                     rc;
2695         ENTRY;
2696
2697         LASSERT(th);
2698         oh = container_of(th, struct osd_thandle, ot_super);
2699         LASSERT(oh->ot_handle->h_transaction != NULL);
2700
2701         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, type);
2702         if (IS_ERR(local)) {
2703                 CERROR("%s: create local error %d\n", osd_name(osd),
2704                        (int)PTR_ERR(local));
2705                 RETURN(local);
2706         }
2707
2708         /* Set special LMA flag for local agent inode */
2709         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
2710         if (rc != 0) {
2711                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
2712                        osd_name(osd), PFID(fid), rc);
2713                 RETURN(ERR_PTR(rc));
2714         }
2715
2716         if (!S_ISDIR(type))
2717                 RETURN(local);
2718
2719         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
2720                                          lu_object_fid(&pobj->oo_dt.do_lu),
2721                                          fid, oh);
2722         if (rc != 0) {
2723                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
2724                         osd_name(osd), PFID(fid), rc);
2725                 RETURN(ERR_PTR(rc));
2726         }
2727
2728         RETURN(local);
2729 }
2730
2731 /**
2732  * Delete local agent inode for remote entry
2733  */
2734 static int osd_delete_local_agent_inode(const struct lu_env *env,
2735                                         struct osd_device *osd,
2736                                         const struct lu_fid *fid,
2737                                         __u32 ino, struct osd_thandle *oh)
2738 {
2739         struct osd_thread_info  *oti = osd_oti_get(env);
2740         struct osd_inode_id     *id = &oti->oti_id;
2741         struct inode            *inode;
2742         ENTRY;
2743
2744         id->oii_ino = le32_to_cpu(ino);
2745         id->oii_gen = OSD_OII_NOGEN;
2746         inode = osd_iget(oti, osd, id);
2747         if (IS_ERR(inode)) {
2748                 CERROR("%s: iget error "DFID" id %u:%u\n", osd_name(osd),
2749                        PFID(fid), id->oii_ino, id->oii_gen);
2750                 RETURN(PTR_ERR(inode));
2751         }
2752
2753         clear_nlink(inode);
2754         mark_inode_dirty(inode);
2755         CDEBUG(D_INODE, "%s: delete remote inode "DFID" %lu\n",
2756                 osd_name(osd), PFID(fid), inode->i_ino);
2757         iput(inode);
2758         RETURN(0);
2759 }
2760
2761 /**
2762  * OSD layer object create function for interoperability mode (b11826).
2763  * This is mostly similar to osd_object_create(). Only difference being, fid is
2764  * inserted into inode ea here.
2765  *
2766  * \retval   0, on success
2767  * \retval -ve, on error
2768  */
2769 static int osd_object_ea_create(const struct lu_env *env, struct dt_object *dt,
2770                                 struct lu_attr *attr,
2771                                 struct dt_allocation_hint *hint,
2772                                 struct dt_object_format *dof,
2773                                 struct thandle *th)
2774 {
2775         const struct lu_fid     *fid    = lu_object_fid(&dt->do_lu);
2776         struct osd_object       *obj    = osd_dt_obj(dt);
2777         struct osd_thread_info  *info   = osd_oti_get(env);
2778         int                      result;
2779
2780         ENTRY;
2781
2782         if (dt_object_exists(dt))
2783                 RETURN(-EEXIST);
2784
2785         LASSERT(osd_invariant(obj));
2786         LASSERT(!dt_object_remote(dt));
2787         LASSERT(osd_write_locked(env, obj));
2788         LASSERT(th != NULL);
2789
2790         if (unlikely(fid_is_acct(fid)))
2791                 /* Quota files can't be created from the kernel any more,
2792                  * 'tune2fs -O quota' will take care of creating them */
2793                 RETURN(-EPERM);
2794
2795         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2796         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2797
2798         result = __osd_object_create(info, obj, attr, hint, dof, th);
2799         if (result == 0)
2800                 result = osd_ea_fid_set(info, obj->oo_inode, fid,
2801                                 fid_is_on_ost(info, osd_obj2dev(obj),
2802                                               fid, OI_CHECK_FLD) ?
2803                                 LMAC_FID_ON_OST : 0, 0);
2804
2805         if (result == 0)
2806                 result = __osd_oi_insert(env, obj, fid, th);
2807
2808         LASSERT(ergo(result == 0,
2809                      dt_object_exists(dt) && !dt_object_remote(dt)));
2810         LINVRNT(osd_invariant(obj));
2811         RETURN(result);
2812 }
2813
2814 static int osd_declare_object_ref_add(const struct lu_env *env,
2815                                       struct dt_object *dt,
2816                                       struct thandle *handle)
2817 {
2818         struct osd_thandle       *oh;
2819
2820         /* it's possible that object doesn't exist yet */
2821         LASSERT(handle != NULL);
2822
2823         oh = container_of0(handle, struct osd_thandle, ot_super);
2824         LASSERT(oh->ot_handle == NULL);
2825
2826         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
2827                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2828
2829         return 0;
2830 }
2831
2832 /*
2833  * Concurrency: @dt is write locked.
2834  */
2835 static int osd_object_ref_add(const struct lu_env *env,
2836                               struct dt_object *dt, struct thandle *th)
2837 {
2838         struct osd_object  *obj = osd_dt_obj(dt);
2839         struct inode       *inode = obj->oo_inode;
2840         struct osd_thandle *oh;
2841         int                 rc = 0;
2842
2843         if (!dt_object_exists(dt))
2844                 return -ENOENT;
2845
2846         LINVRNT(osd_invariant(obj));
2847         LASSERT(!dt_object_remote(dt));
2848         LASSERT(osd_write_locked(env, obj));
2849         LASSERT(th != NULL);
2850
2851         oh = container_of0(th, struct osd_thandle, ot_super);
2852         LASSERT(oh->ot_handle != NULL);
2853
2854         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
2855
2856         CDEBUG(D_INODE, DFID" increase nlink %d\n",
2857                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
2858         /*
2859          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
2860          * (65000) subdirectories by storing "1" in i_nlink if the link count
2861          * would otherwise overflow. Directory tranversal tools understand
2862          * that (st_nlink == 1) indicates that the filesystem dose not track
2863          * hard links count on the directory, and will not abort subdirectory
2864          * scanning early once (st_nlink - 2) subdirs have been found.
2865          *
2866          * This also has to properly handle the case of inodes with nlink == 0
2867          * in case they are being linked into the PENDING directory
2868          */
2869         spin_lock(&obj->oo_guard);
2870         if (unlikely(inode->i_nlink == 0))
2871                 /* inc_nlink from 0 may cause WARN_ON */
2872                 set_nlink(inode, 1);
2873         else {
2874                 ldiskfs_inc_count(oh->ot_handle, inode);
2875                 if (!S_ISDIR(inode->i_mode))
2876                         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
2877         }
2878         spin_unlock(&obj->oo_guard);
2879
2880         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2881         LINVRNT(osd_invariant(obj));
2882
2883         return rc;
2884 }
2885
2886 static int osd_declare_object_ref_del(const struct lu_env *env,
2887                                       struct dt_object *dt,
2888                                       struct thandle *handle)
2889 {
2890         struct osd_thandle *oh;
2891
2892         LASSERT(!dt_object_remote(dt));
2893         LASSERT(handle != NULL);
2894
2895         oh = container_of0(handle, struct osd_thandle, ot_super);
2896         LASSERT(oh->ot_handle == NULL);
2897
2898         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
2899                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2900
2901         return 0;
2902 }
2903
2904 /*
2905  * Concurrency: @dt is write locked.
2906  */
2907 static int osd_object_ref_del(const struct lu_env *env, struct dt_object *dt,
2908                               struct thandle *th)
2909 {
2910         struct osd_object       *obj = osd_dt_obj(dt);
2911         struct inode            *inode = obj->oo_inode;
2912         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
2913         struct osd_thandle      *oh;
2914
2915         if (!dt_object_exists(dt))
2916                 return -ENOENT;
2917
2918         LINVRNT(osd_invariant(obj));
2919         LASSERT(!dt_object_remote(dt));
2920         LASSERT(osd_write_locked(env, obj));
2921         LASSERT(th != NULL);
2922
2923         oh = container_of0(th, struct osd_thandle, ot_super);
2924         LASSERT(oh->ot_handle != NULL);
2925
2926         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
2927
2928         spin_lock(&obj->oo_guard);
2929         /* That can be result of upgrade from old Lustre version and
2930          * applied only to local files.  Just skip this ref_del call.
2931          * ext4_unlink() only treats this as a warning, don't LASSERT here.*/
2932         if (inode->i_nlink == 0) {
2933                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
2934                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
2935                              ", maybe an upgraded file? (LU-3915)\n",
2936                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
2937                 spin_unlock(&obj->oo_guard);
2938                 return 0;
2939         }
2940
2941         CDEBUG(D_INODE, DFID" decrease nlink %d\n",
2942                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
2943
2944         ldiskfs_dec_count(oh->ot_handle, inode);
2945         spin_unlock(&obj->oo_guard);
2946
2947         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2948         LINVRNT(osd_invariant(obj));
2949
2950         return 0;
2951 }
2952
2953 /*
2954  * Get the 64-bit version for an inode.
2955  */
2956 static int osd_object_version_get(const struct lu_env *env,
2957                                   struct dt_object *dt, dt_obj_version_t *ver)
2958 {
2959         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2960
2961         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
2962                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2963         *ver = LDISKFS_I(inode)->i_fs_version;
2964         return 0;
2965 }
2966
2967 /*
2968  * Concurrency: @dt is read locked.
2969  */
2970 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
2971                          struct lu_buf *buf, const char *name,
2972                          struct lustre_capa *capa)
2973 {
2974         struct osd_object      *obj    = osd_dt_obj(dt);
2975         struct inode           *inode  = obj->oo_inode;
2976         struct osd_thread_info *info   = osd_oti_get(env);
2977         struct dentry          *dentry = &info->oti_obj_dentry;
2978
2979         /* version get is not real XATTR but uses xattr API */
2980         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2981                 /* for version we are just using xattr API but change inode
2982                  * field instead */
2983                 if (buf->lb_len == 0)
2984                         return sizeof(dt_obj_version_t);
2985
2986                 if (buf->lb_len < sizeof(dt_obj_version_t))
2987                         return -ERANGE;
2988
2989                 osd_object_version_get(env, dt, buf->lb_buf);
2990
2991                 return sizeof(dt_obj_version_t);
2992         }
2993
2994         if (!dt_object_exists(dt))
2995                 return -ENOENT;
2996
2997         LASSERT(!dt_object_remote(dt));
2998         LASSERT(inode->i_op != NULL);
2999         LASSERT(inode->i_op->getxattr != NULL);
3000
3001         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
3002                 return -EACCES;
3003
3004         return __osd_xattr_get(inode, dentry, name, buf->lb_buf, buf->lb_len);
3005 }
3006
3007
3008 static int osd_declare_xattr_set(const struct lu_env *env,
3009                                  struct dt_object *dt,
3010                                  const struct lu_buf *buf, const char *name,
3011                                  int fl, struct thandle *handle)
3012 {
3013         struct osd_thandle *oh;
3014         int credits;
3015         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3016
3017         LASSERT(handle != NULL);
3018
3019         oh = container_of0(handle, struct osd_thandle, ot_super);
3020         LASSERT(oh->ot_handle == NULL);
3021
3022         /* optimistic optimization: LMA is set first and usually fit inode */
3023         if (strcmp(name, XATTR_NAME_LMA) == 0) {
3024                 if (dt_object_exists(dt))
3025                         credits = 0;
3026                 else
3027                         credits = 1;
3028         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
3029                 credits = 1;
3030         } else {
3031                 credits = osd_dto_credits_noquota[DTO_XATTR_SET];
3032                 if (buf && buf->lb_len > sb->s_blocksize) {
3033                         credits *= (buf->lb_len + sb->s_blocksize - 1) >>
3034                                         sb->s_blocksize_bits;
3035                 }
3036                 /*
3037                  * xattr set may involve inode quota change, reserve credits for
3038                  * dquot_initialize()
3039                  */
3040                 oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
3041         }
3042
3043         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
3044
3045         return 0;
3046 }
3047
3048 /*
3049  * Set the 64-bit version for object
3050  */
3051 static void osd_object_version_set(const struct lu_env *env,
3052                                    struct dt_object *dt,
3053                                    dt_obj_version_t *new_version)
3054 {
3055         struct inode *inode = osd_dt_obj(dt)->oo_inode;
3056
3057         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
3058                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
3059
3060         LDISKFS_I(inode)->i_fs_version = *new_version;
3061         /** Version is set after all inode operations are finished,
3062          *  so we should mark it dirty here */
3063         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3064 }
3065
3066 /*
3067  * Concurrency: @dt is write locked.
3068  */
3069 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
3070                          const struct lu_buf *buf, const char *name, int fl,
3071                          struct thandle *handle, struct lustre_capa *capa)
3072 {
3073         struct osd_object      *obj      = osd_dt_obj(dt);
3074         struct inode           *inode    = obj->oo_inode;
3075         struct osd_thread_info *info     = osd_oti_get(env);
3076         int                     fs_flags = 0;
3077         ENTRY;
3078
3079         LASSERT(handle != NULL);
3080
3081         /* version set is not real XATTR */
3082         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
3083                 /* for version we are just using xattr API but change inode
3084                  * field instead */
3085                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
3086                 osd_object_version_set(env, dt, buf->lb_buf);
3087                 return sizeof(dt_obj_version_t);
3088         }
3089
3090         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
3091                 return -EACCES;
3092
3093         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zu\n",
3094                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
3095
3096         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3097         if (fl & LU_XATTR_REPLACE)
3098                 fs_flags |= XATTR_REPLACE;
3099
3100         if (fl & LU_XATTR_CREATE)
3101                 fs_flags |= XATTR_CREATE;
3102
3103         if (strcmp(name, XATTR_NAME_LMV) == 0) {
3104                 struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
3105                 int                      rc;
3106
3107                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
3108                 if (rc != 0)
3109                         RETURN(rc);
3110
3111                 lma->lma_incompat |= LMAI_STRIPED;
3112                 lustre_lma_swab(lma);
3113                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3114                                      sizeof(*lma), XATTR_REPLACE);
3115                 if (rc != 0)
3116                         RETURN(rc);
3117         }
3118
3119         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LINKEA_OVERFLOW) &&
3120             strcmp(name, XATTR_NAME_LINK) == 0)
3121                 return -ENOSPC;
3122
3123         return __osd_xattr_set(info, inode, name, buf->lb_buf, buf->lb_len,
3124                                fs_flags);
3125 }
3126
3127 /*
3128  * Concurrency: @dt is read locked.
3129  */
3130 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
3131                           const struct lu_buf *buf, struct lustre_capa *capa)
3132 {
3133         struct osd_object      *obj    = osd_dt_obj(dt);
3134         struct inode           *inode  = obj->oo_inode;
3135         struct osd_thread_info *info   = osd_oti_get(env);
3136         struct dentry          *dentry = &info->oti_obj_dentry;
3137
3138         if (!dt_object_exists(dt))
3139                 return -ENOENT;
3140
3141         LASSERT(!dt_object_remote(dt));
3142         LASSERT(inode->i_op != NULL);
3143         LASSERT(inode->i_op->listxattr != NULL);
3144
3145         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
3146                 return -EACCES;
3147
3148         dentry->d_inode = inode;
3149         dentry->d_sb = inode->i_sb;
3150         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
3151 }
3152
3153 static int osd_declare_xattr_del(const struct lu_env *env,
3154                                  struct dt_object *dt, const char *name,
3155                                  struct thandle *handle)
3156 {
3157         struct osd_thandle *oh;
3158         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3159
3160         LASSERT(!dt_object_remote(dt));
3161         LASSERT(handle != NULL);
3162
3163         oh = container_of0(handle, struct osd_thandle, ot_super);
3164         LASSERT(oh->ot_handle == NULL);
3165
3166         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
3167                              osd_dto_credits_noquota[DTO_XATTR_SET]);
3168         /*
3169          * xattr del may involve inode quota change, reserve credits for
3170          * dquot_initialize()
3171          */
3172         oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
3173
3174         return 0;
3175 }
3176
3177 /*
3178  * Concurrency: @dt is write locked.
3179  */
3180 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
3181                          const char *name, struct thandle *handle,
3182                          struct lustre_capa *capa)
3183 {
3184         struct osd_object      *obj    = osd_dt_obj(dt);
3185         struct inode           *inode  = obj->oo_inode;
3186         struct osd_thread_info *info   = osd_oti_get(env);
3187         struct dentry          *dentry = &info->oti_obj_dentry;
3188         int                     rc;
3189
3190         if (!dt_object_exists(dt))
3191                 return -ENOENT;
3192
3193         LASSERT(!dt_object_remote(dt));
3194         LASSERT(inode->i_op != NULL);
3195         LASSERT(inode->i_op->removexattr != NULL);
3196         LASSERT(handle != NULL);
3197
3198         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
3199                 return -EACCES;
3200
3201         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3202
3203         ll_vfs_dq_init(inode);
3204         dentry->d_inode = inode;
3205         dentry->d_sb = inode->i_sb;
3206         rc = inode->i_op->removexattr(dentry, name);
3207         return rc;
3208 }
3209
3210 static struct obd_capa *osd_capa_get(const struct lu_env *env,
3211                                      struct dt_object *dt,
3212                                      struct lustre_capa *old, __u64 opc)
3213 {
3214         struct osd_thread_info *info = osd_oti_get(env);
3215         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3216         struct osd_object *obj = osd_dt_obj(dt);
3217         struct osd_device *osd = osd_obj2dev(obj);
3218         struct lustre_capa_key *key = &info->oti_capa_key;
3219         struct lustre_capa *capa = &info->oti_capa;
3220         struct obd_capa *oc;
3221         struct lu_capainfo *lci;
3222         int rc;
3223         ENTRY;
3224
3225         if (!osd->od_fl_capa)
3226                 RETURN(ERR_PTR(-ENOENT));
3227
3228         if (!dt_object_exists(dt))
3229                 RETURN(ERR_PTR(-ENOENT));
3230
3231         LASSERT(!dt_object_remote(dt));
3232         LINVRNT(osd_invariant(obj));
3233
3234         /* renewal sanity check */
3235         if (old && osd_object_auth(env, dt, old, opc))
3236                 RETURN(ERR_PTR(-EACCES));
3237
3238         lci = lu_capainfo_get(env);
3239         if (unlikely(lci == NULL))
3240                 RETURN(ERR_PTR(-ENOENT));
3241
3242         switch (lci->lci_auth) {
3243         case LC_ID_NONE:
3244                 RETURN(NULL);
3245         case LC_ID_PLAIN:
3246                 capa->lc_uid = i_uid_read(obj->oo_inode);
3247                 capa->lc_gid = i_gid_read(obj->oo_inode);
3248                 capa->lc_flags = LC_ID_PLAIN;
3249                 break;
3250         case LC_ID_CONVERT: {
3251                 __u32 d[4], s[4];
3252
3253                 s[0] = i_uid_read(obj->oo_inode);
3254                 cfs_get_random_bytes(&(s[1]), sizeof(__u32));
3255                 s[2] = i_uid_read(obj->oo_inode);
3256                 cfs_get_random_bytes(&(s[3]), sizeof(__u32));
3257                 rc = capa_encrypt_id(d, s, key->lk_key, CAPA_HMAC_KEY_MAX_LEN);
3258                 if (unlikely(rc))
3259                         RETURN(ERR_PTR(rc));
3260
3261                 capa->lc_uid   = ((__u64)d[1] << 32) | d[0];
3262                 capa->lc_gid   = ((__u64)d[3] << 32) | d[2];
3263                 capa->lc_flags = LC_ID_CONVERT;
3264                 break;
3265         }
3266         default:
3267                 RETURN(ERR_PTR(-EINVAL));
3268         }
3269
3270         capa->lc_fid = *fid;
3271         capa->lc_opc = opc;
3272         capa->lc_flags |= osd->od_capa_alg << 24;
3273         capa->lc_timeout = osd->od_capa_timeout;
3274         capa->lc_expiry = 0;
3275
3276         oc = capa_lookup(osd->od_capa_hash, capa, 1);
3277         if (oc) {
3278                 LASSERT(!capa_is_expired(oc));
3279                 RETURN(oc);
3280         }
3281
3282         spin_lock(&capa_lock);
3283         *key = osd->od_capa_keys[1];
3284         spin_unlock(&capa_lock);
3285
3286         capa->lc_keyid = key->lk_keyid;
3287         capa->lc_expiry = cfs_time_current_sec() + osd->od_capa_timeout;
3288
3289         rc = capa_hmac(capa->lc_hmac, capa, key->lk_key);
3290         if (rc) {
3291                 DEBUG_CAPA(D_ERROR, capa, "HMAC failed: %d for", rc);
3292                 RETURN(ERR_PTR(rc));
3293         }
3294
3295         oc = capa_add(osd->od_capa_hash, capa);
3296         RETURN(oc);
3297 }
3298
3299 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt,
3300                            __u64 start, __u64 end)
3301 {
3302         struct osd_object       *obj    = osd_dt_obj(dt);
3303         struct inode            *inode  = obj->oo_inode;
3304         struct osd_thread_info  *info   = osd_oti_get(env);
3305         struct dentry           *dentry = &info->oti_obj_dentry;
3306         struct file             *file   = &info->oti_file;
3307         int                     rc;
3308
3309         ENTRY;
3310
3311         dentry->d_inode = inode;
3312         dentry->d_sb = inode->i_sb;
3313         file->f_dentry = dentry;
3314         file->f_mapping = inode->i_mapping;
3315         file->f_op = inode->i_fop;
3316         set_file_inode(file, inode);
3317
3318         rc = ll_vfs_fsync_range(file, start, end, 0);
3319
3320         RETURN(rc);
3321 }
3322
3323 static int osd_data_get(const struct lu_env *env, struct dt_object *dt,
3324                         void **data)
3325 {
3326         struct osd_object *obj = osd_dt_obj(dt);
3327         ENTRY;
3328
3329         *data = (void *)obj->oo_inode;
3330         RETURN(0);
3331 }
3332
3333 /*
3334  * Index operations.
3335  */
3336
3337 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
3338                            const struct dt_index_features *feat)
3339 {
3340         struct iam_descr *descr;
3341
3342         if (osd_object_is_root(o))
3343                 return feat == &dt_directory_features;
3344
3345         LASSERT(o->oo_dir != NULL);
3346
3347         descr = o->oo_dir->od_container.ic_descr;
3348         if (feat == &dt_directory_features) {
3349                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
3350                         return 1;
3351                 else
3352                         return 0;
3353         } else {
3354                 return
3355                         feat->dif_keysize_min <= descr->id_key_size &&
3356                         descr->id_key_size <= feat->dif_keysize_max &&
3357                         feat->dif_recsize_min <= descr->id_rec_size &&
3358                         descr->id_rec_size <= feat->dif_recsize_max &&
3359                         !(feat->dif_flags & (DT_IND_VARKEY |
3360                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
3361                         ergo(feat->dif_flags & DT_IND_UPDATE,
3362                              1 /* XXX check that object (and file system) is
3363                                 * writable */);
3364         }
3365 }
3366
3367 static int osd_iam_container_init(const struct lu_env *env,
3368                                   struct osd_object *obj,
3369                                   struct osd_directory *dir)
3370 {
3371         struct iam_container *bag = &dir->od_container;
3372         int result;
3373
3374         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
3375         if (result != 0)
3376                 return result;
3377
3378         result = iam_container_setup(bag);
3379         if (result == 0)
3380                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
3381         else
3382                 iam_container_fini(bag);
3383
3384         return result;
3385 }
3386
3387
3388 /*
3389  * Concurrency: no external locking is necessary.
3390  */
3391 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
3392                          const struct dt_index_features *feat)
3393 {
3394         int                      result;
3395         int                      skip_iam = 0;
3396         struct osd_object       *obj = osd_dt_obj(dt);
3397
3398         LINVRNT(osd_invariant(obj));
3399
3400         if (osd_object_is_root(obj)) {
3401                 dt->do_index_ops = &osd_index_ea_ops;
3402                 result = 0;
3403         } else if (feat == &dt_directory_features) {
3404                 dt->do_index_ops = &osd_index_ea_ops;
3405                 if (obj->oo_inode != NULL && S_ISDIR(obj->oo_inode->i_mode))
3406                         result = 0;
3407                 else
3408                         result = -ENOTDIR;
3409                 skip_iam = 1;
3410         } else if (unlikely(feat == &dt_otable_features)) {
3411                 dt->do_index_ops = &osd_otable_ops;
3412                 return 0;
3413         } else if (unlikely(feat == &dt_acct_features)) {
3414                 dt->do_index_ops = &osd_acct_index_ops;
3415                 result = 0;
3416                 skip_iam = 1;
3417         } else if (!osd_has_index(obj)) {
3418                 struct osd_directory *dir;
3419
3420                 OBD_ALLOC_PTR(dir);
3421                 if (dir != NULL) {
3422
3423                         spin_lock(&obj->oo_guard);
3424                         if (obj->oo_dir == NULL)
3425                                 obj->oo_dir = dir;
3426                         else
3427                                 /*
3428                                  * Concurrent thread allocated container data.
3429                                  */
3430                                 OBD_FREE_PTR(dir);
3431                         spin_unlock(&obj->oo_guard);
3432                         /*
3433                          * Now, that we have container data, serialize its
3434                          * initialization.
3435                          */
3436                         down_write(&obj->oo_ext_idx_sem);
3437                         /*
3438                          * recheck under lock.
3439                          */
3440                         if (!osd_has_index(obj))
3441                                 result = osd_iam_container_init(env, obj,
3442                                                                 obj->oo_dir);
3443                         else
3444                                 result = 0;
3445                         up_write(&obj->oo_ext_idx_sem);
3446                 } else {
3447                         result = -ENOMEM;
3448                 }
3449         } else {
3450                 result = 0;
3451         }
3452
3453         if (result == 0 && skip_iam == 0) {
3454                 if (!osd_iam_index_probe(env, obj, feat))
3455                         result = -ENOTDIR;
3456         }
3457         LINVRNT(osd_invariant(obj));
3458
3459         if (result == 0 && is_quota_glb_feat(feat) &&
3460             fid_seq(lu_object_fid(&dt->do_lu)) == FID_SEQ_QUOTA_GLB)
3461                 result = osd_quota_migration(env, dt, feat);
3462
3463         return result;
3464 }
3465
3466 static int osd_otable_it_attr_get(const struct lu_env *env,
3467                                  struct dt_object *dt,
3468                                  struct lu_attr *attr,
3469                                  struct lustre_capa *capa)
3470 {
3471         attr->la_valid = 0;
3472         return 0;
3473 }
3474
3475 static const struct dt_object_operations osd_obj_ops = {
3476         .do_read_lock         = osd_object_read_lock,
3477         .do_write_lock        = osd_object_write_lock,
3478         .do_read_unlock       = osd_object_read_unlock,
3479         .do_write_unlock      = osd_object_write_unlock,
3480         .do_write_locked      = osd_object_write_locked,
3481         .do_attr_get          = osd_attr_get,
3482         .do_declare_attr_set  = osd_declare_attr_set,
3483         .do_attr_set          = osd_attr_set,
3484         .do_ah_init           = osd_ah_init,
3485         .do_declare_create    = osd_declare_object_create,
3486         .do_create            = osd_object_create,
3487         .do_declare_destroy   = osd_declare_object_destroy,
3488         .do_destroy           = osd_object_destroy,
3489         .do_index_try         = osd_index_try,
3490         .do_declare_ref_add   = osd_declare_object_ref_add,
3491         .do_ref_add           = osd_object_ref_add,
3492         .do_declare_ref_del   = osd_declare_object_ref_del,
3493         .do_ref_del           = osd_object_ref_del,
3494         .do_xattr_get         = osd_xattr_get,
3495         .do_declare_xattr_set = osd_declare_xattr_set,
3496         .do_xattr_set         = osd_xattr_set,
3497         .do_declare_xattr_del = osd_declare_xattr_del,
3498         .do_xattr_del         = osd_xattr_del,
3499         .do_xattr_list        = osd_xattr_list,
3500         .do_capa_get          = osd_capa_get,
3501         .do_object_sync       = osd_object_sync,
3502         .do_data_get          = osd_data_get,
3503 };
3504
3505 /**
3506  * dt_object_operations for interoperability mode
3507  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
3508  */
3509 static const struct dt_object_operations osd_obj_ea_ops = {
3510         .do_read_lock         = osd_object_read_lock,
3511         .do_write_lock        = osd_object_write_lock,
3512         .do_read_unlock       = osd_object_read_unlock,
3513         .do_write_unlock      = osd_object_write_unlock,
3514         .do_write_locked      = osd_object_write_locked,
3515         .do_attr_get          = osd_attr_get,
3516         .do_declare_attr_set  = osd_declare_attr_set,
3517         .do_attr_set          = osd_attr_set,
3518         .do_ah_init           = osd_ah_init,
3519         .do_declare_create    = osd_declare_object_create,
3520         .do_create            = osd_object_ea_create,
3521         .do_declare_destroy   = osd_declare_object_destroy,
3522         .do_destroy           = osd_object_destroy,
3523         .do_index_try         = osd_index_try,
3524         .do_declare_ref_add   = osd_declare_object_ref_add,
3525         .do_ref_add           = osd_object_ref_add,
3526         .do_declare_ref_del   = osd_declare_object_ref_del,
3527         .do_ref_del           = osd_object_ref_del,
3528         .do_xattr_get         = osd_xattr_get,
3529         .do_declare_xattr_set = osd_declare_xattr_set,
3530         .do_xattr_set         = osd_xattr_set,
3531         .do_declare_xattr_del = osd_declare_xattr_del,
3532         .do_xattr_del         = osd_xattr_del,
3533         .do_xattr_list        = osd_xattr_list,
3534         .do_capa_get          = osd_capa_get,
3535         .do_object_sync       = osd_object_sync,
3536         .do_data_get          = osd_data_get,
3537 };
3538
3539 static const struct dt_object_operations osd_obj_otable_it_ops = {
3540         .do_attr_get    = osd_otable_it_attr_get,
3541         .do_index_try   = osd_index_try,
3542 };
3543
3544 static int osd_index_declare_iam_delete(const struct lu_env *env,
3545                                         struct dt_object *dt,
3546                                         const struct dt_key *key,
3547                                         struct thandle *handle)
3548 {
3549         struct osd_thandle    *oh;
3550
3551         oh = container_of0(handle, struct osd_thandle, ot_super);
3552         LASSERT(oh->ot_handle == NULL);
3553
3554         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3555                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3556
3557         return 0;
3558 }
3559
3560 /**
3561  *      delete a (key, value) pair from index \a dt specified by \a key
3562  *
3563  *      \param  dt      osd index object
3564  *      \param  key     key for index
3565  *      \param  rec     record reference
3566  *      \param  handle  transaction handler
3567  *
3568  *      \retval  0  success
3569  *      \retval -ve   failure
3570  */
3571 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
3572                                 const struct dt_key *key,
3573                                 struct thandle *handle,
3574                                 struct lustre_capa *capa)
3575 {
3576         struct osd_thread_info *oti = osd_oti_get(env);
3577         struct osd_object      *obj = osd_dt_obj(dt);
3578         struct osd_thandle     *oh;
3579         struct iam_path_descr  *ipd;
3580         struct iam_container   *bag = &obj->oo_dir->od_container;
3581         int                     rc;
3582         ENTRY;
3583
3584         if (!dt_object_exists(dt))
3585                 RETURN(-ENOENT);
3586
3587         LINVRNT(osd_invariant(obj));
3588         LASSERT(!dt_object_remote(dt));
3589         LASSERT(bag->ic_object == obj->oo_inode);
3590         LASSERT(handle != NULL);
3591
3592         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3593                 RETURN(-EACCES);
3594
3595         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3596
3597         ipd = osd_idx_ipd_get(env, bag);
3598         if (unlikely(ipd == NULL))
3599                 RETURN(-ENOMEM);
3600
3601         oh = container_of0(handle, struct osd_thandle, ot_super);
3602         LASSERT(oh->ot_handle != NULL);
3603         LASSERT(oh->ot_handle->h_transaction != NULL);
3604
3605         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3606                 /* swab quota uid/gid provided by caller */
3607                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3608                 key = (const struct dt_key *)&oti->oti_quota_id;
3609         }
3610
3611         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
3612         osd_ipd_put(env, bag, ipd);
3613         LINVRNT(osd_invariant(obj));
3614         RETURN(rc);
3615 }
3616
3617 static int osd_index_declare_ea_delete(const struct lu_env *env,
3618                                        struct dt_object *dt,
3619                                        const struct dt_key *key,
3620                                        struct thandle *handle)
3621 {
3622         struct osd_thandle *oh;
3623         struct inode       *inode;
3624         int                 rc;
3625         ENTRY;
3626
3627         LASSERT(!dt_object_remote(dt));
3628         LASSERT(handle != NULL);
3629
3630         oh = container_of0(handle, struct osd_thandle, ot_super);
3631         LASSERT(oh->ot_handle == NULL);
3632
3633         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3634                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3635
3636         inode = osd_dt_obj(dt)->oo_inode;
3637         LASSERT(inode);
3638
3639         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3640                                    0, oh, osd_dt_obj(dt), true, NULL, false);
3641         RETURN(rc);
3642 }
3643
3644 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3645                                           struct dt_rec *fid)
3646 {
3647         struct osd_fid_pack *rec;
3648         int                  rc = -ENODATA;
3649
3650         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3651                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3652                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3653         }
3654         return rc;
3655 }
3656
3657 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
3658                           const struct lu_fid *fid)
3659 {
3660         struct seq_server_site  *ss = osd_seq_site(osd);
3661         ENTRY;
3662
3663         /* FID seqs not in FLDB, must be local seq */
3664         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
3665                 RETURN(0);
3666
3667         /* If FLD is not being initialized yet, it only happens during the
3668          * initialization, likely during mgs initialization, and we assume
3669          * this is local FID. */
3670         if (ss == NULL || ss->ss_server_fld == NULL)
3671                 RETURN(0);
3672
3673         /* Only check the local FLDB here */
3674         if (osd_seq_exists(env, osd, fid_seq(fid)))
3675                 RETURN(0);
3676
3677         RETURN(1);
3678 }
3679
3680 /**
3681  * Index delete function for interoperability mode (b11826).
3682  * It will remove the directory entry added by osd_index_ea_insert().
3683  * This entry is needed to maintain name->fid mapping.
3684  *
3685  * \param key,  key i.e. file entry to be deleted
3686  *
3687  * \retval   0, on success
3688  * \retval -ve, on error
3689  */
3690 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3691                                const struct dt_key *key, struct thandle *handle,
3692                                struct lustre_capa *capa)
3693 {
3694         struct osd_object          *obj = osd_dt_obj(dt);
3695         struct inode               *dir = obj->oo_inode;
3696         struct dentry              *dentry;
3697         struct osd_thandle         *oh;
3698         struct ldiskfs_dir_entry_2 *de = NULL;
3699         struct buffer_head         *bh;
3700         struct htree_lock          *hlock = NULL;
3701         struct lu_fid              *fid = &osd_oti_get(env)->oti_fid;
3702         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
3703         int                        rc;
3704         ENTRY;
3705
3706         if (!dt_object_exists(dt))
3707                 RETURN(-ENOENT);
3708
3709         LINVRNT(osd_invariant(obj));
3710         LASSERT(!dt_object_remote(dt));
3711         LASSERT(handle != NULL);
3712
3713         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3714
3715         oh = container_of(handle, struct osd_thandle, ot_super);
3716         LASSERT(oh->ot_handle != NULL);
3717         LASSERT(oh->ot_handle->h_transaction != NULL);
3718
3719         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3720                 RETURN(-EACCES);
3721
3722         ll_vfs_dq_init(dir);
3723         dentry = osd_child_dentry_get(env, obj,
3724                                       (char *)key, strlen((char *)key));
3725
3726         if (obj->oo_hl_head != NULL) {
3727                 hlock = osd_oti_get(env)->oti_hlock;
3728                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3729                                    dir, LDISKFS_HLOCK_DEL);
3730         } else {
3731                 down_write(&obj->oo_ext_idx_sem);
3732         }
3733
3734         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
3735         if (bh) {
3736                 __u32 ino = 0;
3737
3738                 /* If this is not the ".." entry, it might be a remote DNE
3739                  * entry and  we need to check if the FID is for a remote
3740                  * MDT.  If the FID is  not in the directory entry (e.g.
3741                  * upgraded 1.8 filesystem without dirdata enabled) then
3742                  * we need to get the FID from the LMA. For a remote directory
3743                  * there HAS to be an LMA, it cannot be an IGIF inode in this
3744                  * case.
3745                  *
3746                  * Delete the entry before the agent inode in order to
3747                  * simplify error handling.  At worst an error after deleting
3748                  * the entry first might leak the agent inode afterward. The
3749                  * reverse would need filesystem abort in case of error deleting
3750                  * the entry after the agent had been removed, or leave a
3751                  * dangling entry pointing at a random inode. */
3752                 if (strcmp((char *)key, dotdot) != 0) {
3753                         LASSERT(de != NULL);
3754                         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
3755                         /* If Fid is not in dentry, try to get it from LMA */
3756                         if (rc == -ENODATA) {
3757                                 struct osd_inode_id *id;
3758                                 struct inode *inode;
3759
3760                                 /* Before trying to get fid from the inode,
3761                                  * check whether the inode is valid.
3762                                  *
3763                                  * If the inode has been deleted, do not go
3764                                  * ahead to do osd_ea_fid_get, which will set
3765                                  * the inode to bad inode, which might cause
3766                                  * the inode to be deleted uncorrectly */
3767                                 inode = ldiskfs_iget(osd_sb(osd),
3768                                                      le32_to_cpu(de->inode));
3769                                 if (IS_ERR(inode)) {
3770                                         CDEBUG(D_INODE, "%s: "DFID"get inode"
3771                                                "error.\n", osd_name(osd),
3772                                                PFID(fid));
3773                                         rc = PTR_ERR(inode);
3774                                 } else {
3775                                         if (likely(inode->i_nlink != 0)) {
3776                                                 id = &osd_oti_get(env)->oti_id;
3777                                                 rc = osd_ea_fid_get(env, obj,
3778                                                         le32_to_cpu(de->inode),
3779                                                                     fid, id);
3780                                         } else {
3781                                                 CDEBUG(D_INFO, "%s: %u "DFID
3782                                                        "deleted.\n",
3783                                                        osd_name(osd),
3784                                                        le32_to_cpu(de->inode),
3785                                                        PFID(fid));
3786                                                 rc = -ESTALE;
3787                                         }
3788                                         iput(inode);
3789                                 }
3790                         }
3791                         if (rc == 0 &&
3792                             unlikely(osd_remote_fid(env, osd, fid)))
3793                                 /* Need to delete agent inode */
3794                                 ino = le32_to_cpu(de->inode);
3795                 }
3796                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
3797                 brelse(bh);
3798                 if (rc == 0 && unlikely(ino != 0)) {
3799                         rc = osd_delete_local_agent_inode(env, osd, fid, ino,
3800                                                           oh);
3801                         if (rc != 0)
3802                                 CERROR("%s: del local inode "DFID": rc = %d\n",
3803                                        osd_name(osd), PFID(fid), rc);
3804                 }
3805         } else {
3806                 rc = -ENOENT;
3807         }
3808         if (hlock != NULL)
3809                 ldiskfs_htree_unlock(hlock);
3810         else
3811                 up_write(&obj->oo_ext_idx_sem);
3812
3813         if (rc != 0)
3814                 GOTO(out, rc);
3815
3816         /* For inode on the remote MDT, .. will point to
3817          * /Agent directory, Check whether it needs to delete
3818          * from agent directory */
3819         if (unlikely(strcmp((char *)key, dotdot) == 0)) {
3820                 rc = osd_delete_from_remote_parent(env, osd_obj2dev(obj), obj,
3821                                                    oh);
3822                 if (rc != 0 && rc != -ENOENT) {
3823                         CERROR("%s: delete agent inode "DFID": rc = %d\n",
3824                                osd_name(osd), PFID(fid), rc);
3825                 }
3826
3827                 if (rc == -ENOENT)
3828                         rc = 0;
3829
3830                 GOTO(out, rc);
3831         }
3832 out:
3833
3834         LASSERT(osd_invariant(obj));
3835         RETURN(rc);
3836 }
3837
3838 /**
3839  *      Lookup index for \a key and copy record to \a rec.
3840  *
3841  *      \param  dt      osd index object
3842  *      \param  key     key for index
3843  *      \param  rec     record reference
3844  *
3845  *      \retval  +ve  success : exact mach
3846  *      \retval  0    return record with key not greater than \a key
3847  *      \retval -ve   failure
3848  */
3849 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
3850                                 struct dt_rec *rec, const struct dt_key *key,
3851                                 struct lustre_capa *capa)
3852 {
3853         struct osd_object      *obj = osd_dt_obj(dt);
3854         struct iam_path_descr  *ipd;
3855         struct iam_container   *bag = &obj->oo_dir->od_container;
3856         struct osd_thread_info *oti = osd_oti_get(env);
3857         struct iam_iterator    *it = &oti->oti_idx_it;
3858         struct iam_rec         *iam_rec;
3859         int                     rc;
3860         ENTRY;
3861
3862         if (!dt_object_exists(dt))
3863                 RETURN(-ENOENT);
3864
3865         LASSERT(osd_invariant(obj));
3866         LASSERT(!dt_object_remote(dt));
3867         LASSERT(bag->ic_object == obj->oo_inode);
3868
3869         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
3870                 RETURN(-EACCES);
3871
3872         ipd = osd_idx_ipd_get(env, bag);
3873         if (IS_ERR(ipd))
3874                 RETURN(-ENOMEM);
3875
3876         /* got ipd now we can start iterator. */
3877         iam_it_init(it, bag, 0, ipd);
3878
3879         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3880                 /* swab quota uid/gid provided by caller */
3881                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3882                 key = (const struct dt_key *)&oti->oti_quota_id;
3883         }
3884
3885         rc = iam_it_get(it, (struct iam_key *)key);
3886         if (rc >= 0) {
3887                 if (S_ISDIR(obj->oo_inode->i_mode))
3888                         iam_rec = (struct iam_rec *)oti->oti_ldp;
3889                 else
3890                         iam_rec = (struct iam_rec *) rec;
3891
3892                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
3893
3894                 if (S_ISDIR(obj->oo_inode->i_mode))
3895                         osd_fid_unpack((struct lu_fid *) rec,
3896                                        (struct osd_fid_pack *)iam_rec);
3897                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
3898                         osd_quota_unpack(obj, rec);
3899         }
3900
3901         iam_it_put(it);
3902         iam_it_fini(it);
3903         osd_ipd_put(env, bag, ipd);
3904
3905         LINVRNT(osd_invariant(obj));
3906
3907         RETURN(rc);
3908 }
3909
3910 static int osd_index_declare_iam_insert(const struct lu_env *env,
3911                                         struct dt_object *dt,
3912                                         const struct dt_rec *rec,
3913                                         const struct dt_key *key,
3914                                         struct thandle *handle)
3915 {
3916         struct osd_thandle *oh;
3917
3918         LASSERT(handle != NULL);
3919
3920         oh = container_of0(handle, struct osd_thandle, ot_super);
3921         LASSERT(oh->ot_handle == NULL);
3922
3923         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3924                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
3925
3926         return 0;
3927 }
3928
3929 /**
3930  *      Inserts (key, value) pair in \a dt index object.
3931  *
3932  *      \param  dt      osd index object
3933  *      \param  key     key for index
3934  *      \param  rec     record reference
3935  *      \param  th      transaction handler
3936  *
3937  *      \retval  0  success
3938  *      \retval -ve failure
3939  */
3940 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
3941                                 const struct dt_rec *rec,
3942                                 const struct dt_key *key, struct thandle *th,
3943                                 struct lustre_capa *capa, int ignore_quota)
3944 {
3945         struct osd_object     *obj = osd_dt_obj(dt);
3946         struct iam_path_descr *ipd;
3947         struct osd_thandle    *oh;
3948         struct iam_container  *bag;
3949         struct osd_thread_info *oti = osd_oti_get(env);
3950         struct iam_rec         *iam_rec;
3951         int                     rc;
3952         ENTRY;
3953
3954         if (!dt_object_exists(dt))
3955                 RETURN(-ENOENT);
3956
3957         LINVRNT(osd_invariant(obj));
3958         LASSERT(!dt_object_remote(dt));
3959
3960         bag = &obj->oo_dir->od_container;
3961         LASSERT(bag->ic_object == obj->oo_inode);
3962         LASSERT(th != NULL);
3963
3964         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3965                 RETURN(-EACCES);
3966
3967         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3968
3969         ipd = osd_idx_ipd_get(env, bag);
3970         if (unlikely(ipd == NULL))
3971                 RETURN(-ENOMEM);
3972
3973         oh = container_of0(th, struct osd_thandle, ot_super);
3974         LASSERT(oh->ot_handle != NULL);
3975         LASSERT(oh->ot_handle->h_transaction != NULL);
3976         if (S_ISDIR(obj->oo_inode->i_mode)) {
3977                 iam_rec = (struct iam_rec *)oti->oti_ldp;
3978                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
3979         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3980                 /* pack quota uid/gid */
3981                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3982                 key = (const struct dt_key *)&oti->oti_quota_id;
3983                 /* pack quota record */
3984                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
3985                 iam_rec = (struct iam_rec *)rec;
3986         } else {
3987                 iam_rec = (struct iam_rec *)rec;
3988         }
3989
3990         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
3991                         iam_rec, ipd);
3992         osd_ipd_put(env, bag, ipd);
3993         LINVRNT(osd_invariant(obj));
3994         RETURN(rc);
3995 }
3996
3997 /**
3998  * Calls ldiskfs_add_entry() to add directory entry
3999  * into the directory. This is required for
4000  * interoperability mode (b11826)
4001  *
4002  * \retval   0, on success
4003  * \retval -ve, on error
4004  */
4005 static int __osd_ea_add_rec(struct osd_thread_info *info,
4006                             struct osd_object *pobj, struct inode  *cinode,
4007                             const char *name, const struct lu_fid *fid,
4008                             struct htree_lock *hlock, struct thandle *th)
4009 {
4010         struct ldiskfs_dentry_param *ldp;
4011         struct dentry               *child;
4012         struct osd_thandle          *oth;
4013         int                          rc;
4014
4015         oth = container_of(th, struct osd_thandle, ot_super);
4016         LASSERT(oth->ot_handle != NULL);
4017         LASSERT(oth->ot_handle->h_transaction != NULL);
4018         LASSERT(pobj->oo_inode);
4019
4020         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
4021         if (unlikely(pobj->oo_inode ==
4022                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
4023                 ldp->edp_magic = 0;
4024         else
4025                 osd_get_ldiskfs_dirent_param(ldp, fid);
4026         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
4027         child->d_fsdata = (void *)ldp;
4028         ll_vfs_dq_init(pobj->oo_inode);
4029         rc = osd_ldiskfs_add_entry(oth->ot_handle, child, cinode, hlock);
4030         if (rc == 0 && OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_TYPE)) {
4031                 struct ldiskfs_dir_entry_2      *de;
4032                 struct buffer_head              *bh;
4033                 int                              rc1;
4034
4035                 bh = osd_ldiskfs_find_entry(pobj->oo_inode, &child->d_name, &de,
4036                                             NULL, hlock);
4037                 if (bh != NULL) {
4038                         rc1 = ldiskfs_journal_get_write_access(oth->ot_handle,
4039                                                                bh);
4040                         if (rc1 == 0) {
4041                                 if (S_ISDIR(cinode->i_mode))
4042                                         de->file_type = LDISKFS_DIRENT_LUFID |
4043                                                         LDISKFS_FT_REG_FILE;
4044                                 else
4045                                         de->file_type = LDISKFS_DIRENT_LUFID |
4046                                                         LDISKFS_FT_DIR;
4047                                 ldiskfs_handle_dirty_metadata(oth->ot_handle,
4048                                                               NULL, bh);
4049                                 brelse(bh);
4050                         }
4051                 }
4052         }
4053
4054         RETURN(rc);
4055 }
4056
4057 /**
4058  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
4059  * into the directory.Also sets flags into osd object to
4060  * indicate dot and dotdot are created. This is required for
4061  * interoperability mode (b11826)
4062  *
4063  * \param dir   directory for dot and dotdot fixup.
4064  * \param obj   child object for linking
4065  *
4066  * \retval   0, on success
4067  * \retval -ve, on error
4068  */
4069 static int osd_add_dot_dotdot(struct osd_thread_info *info,
4070                               struct osd_object *dir,
4071                               struct inode *parent_dir, const char *name,
4072                               const struct lu_fid *dot_fid,
4073                               const struct lu_fid *dot_dot_fid,
4074                               struct thandle *th)
4075 {
4076         struct inode                *inode = dir->oo_inode;
4077         struct osd_thandle          *oth;
4078         int result = 0;
4079
4080         oth = container_of(th, struct osd_thandle, ot_super);
4081         LASSERT(oth->ot_handle->h_transaction != NULL);
4082         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
4083
4084         if (strcmp(name, dot) == 0) {
4085                 if (dir->oo_compat_dot_created) {
4086                         result = -EEXIST;
4087                 } else {
4088                         LASSERT(inode == parent_dir);
4089                         dir->oo_compat_dot_created = 1;
4090                         result = 0;
4091                 }
4092         } else if (strcmp(name, dotdot) == 0) {
4093                 if (!dir->oo_compat_dot_created)
4094                         return -EINVAL;
4095                 /* in case of rename, dotdot is already created */
4096                 if (dir->oo_compat_dotdot_created) {
4097                         return __osd_ea_add_rec(info, dir, parent_dir, name,
4098                                                 dot_dot_fid, NULL, th);
4099                 }
4100
4101                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
4102                         struct lu_fid tfid = *dot_dot_fid;
4103
4104                         tfid.f_oid--;
4105                         result = osd_add_dot_dotdot_internal(info,
4106                                         dir->oo_inode, parent_dir, dot_fid,
4107                                         &tfid, oth);
4108                 } else {
4109                         result = osd_add_dot_dotdot_internal(info,
4110                                         dir->oo_inode, parent_dir, dot_fid,
4111                                         dot_dot_fid, oth);
4112                 }
4113
4114                 if (result == 0)
4115                         dir->oo_compat_dotdot_created = 1;
4116         }
4117
4118         return result;
4119 }
4120
4121
4122 /**
4123  * It will call the appropriate osd_add* function and return the
4124  * value, return by respective functions.
4125  */
4126 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
4127                           struct inode *cinode, const char *name,
4128                           const struct lu_fid *fid, struct thandle *th)
4129 {
4130         struct osd_thread_info *info   = osd_oti_get(env);
4131         struct htree_lock      *hlock;
4132         int                     rc;
4133
4134         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
4135
4136         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
4137                                                    name[2] =='\0'))) {
4138                 if (hlock != NULL) {
4139                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
4140                                            pobj->oo_inode, 0);
4141                 } else {
4142                         down_write(&pobj->oo_ext_idx_sem);
4143                 }
4144
4145                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
4146                                         lu_object_fid(&pobj->oo_dt.do_lu),
4147                                         fid, th);
4148         } else {
4149                 if (hlock != NULL) {
4150                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
4151                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
4152                 } else {
4153                         down_write(&pobj->oo_ext_idx_sem);
4154                 }
4155
4156                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
4157                         struct lu_fid *tfid = &info->oti_fid;
4158
4159                         *tfid = *fid;
4160                         tfid->f_ver = ~0;
4161                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
4162                                               tfid, hlock, th);
4163                 } else {
4164                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
4165                                               hlock, th);
4166                 }
4167         }
4168         if (hlock != NULL)
4169                 ldiskfs_htree_unlock(hlock);
4170         else
4171                 up_write(&pobj->oo_ext_idx_sem);
4172
4173         return rc;
4174 }
4175
4176 static void
4177 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
4178                       struct osd_idmap_cache *oic)
4179 {
4180         struct osd_scrub    *scrub = &dev->od_scrub;
4181         struct lu_fid       *fid   = &oic->oic_fid;
4182         struct osd_inode_id *id    = &oti->oti_id;
4183         int                  once  = 0;
4184         int                  rc;
4185         ENTRY;
4186
4187         if (!fid_is_norm(fid) && !fid_is_igif(fid))
4188                 RETURN_EXIT;
4189
4190         if (scrub->os_pos_current > id->oii_ino)
4191                 RETURN_EXIT;
4192
4193 again:
4194         rc = osd_oi_lookup(oti, dev, fid, id, OI_CHECK_FLD);
4195         if (rc != 0 && rc != -ENOENT)
4196                 RETURN_EXIT;
4197
4198         if (rc == 0 && osd_id_eq(id, &oic->oic_lid))
4199                 RETURN_EXIT;
4200
4201         if (thread_is_running(&scrub->os_thread)) {
4202                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
4203                 /* There is race condition between osd_oi_lookup and OI scrub.
4204                  * The OI scrub finished just after osd_oi_lookup() failure.
4205                  * Under such case, it is unnecessary to trigger OI scrub again,
4206                  * but try to call osd_oi_lookup() again. */
4207                 if (unlikely(rc == -EAGAIN))
4208                         goto again;
4209
4210                 RETURN_EXIT;
4211         }
4212
4213         if (!dev->od_noscrub && ++once == 1) {
4214                 rc = osd_scrub_start(dev, SS_AUTO_PARTIAL | SS_CLEAR_DRYRUN |
4215                                      SS_CLEAR_FAILOUT);
4216                 CDEBUG(D_LFSCK | D_CONSOLE, "%.16s: trigger OI scrub by RPC "
4217                        "for "DFID", rc = %d [2]\n",
4218                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
4219                        PFID(fid), rc);
4220                 if (rc == 0 || rc == -EALREADY)
4221                         goto again;
4222         }
4223
4224         EXIT;
4225 }
4226
4227 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
4228                                struct osd_device *dev,
4229                                struct osd_idmap_cache *oic,
4230                                struct lu_fid *fid, __u32 ino)
4231 {
4232         struct lustre_mdt_attrs *lma   = &oti->oti_mdt_attrs;
4233         struct inode            *inode;
4234         int                      rc;
4235
4236         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
4237         inode = osd_iget(oti, dev, &oic->oic_lid);
4238         if (IS_ERR(inode)) {
4239                 fid_zero(&oic->oic_fid);
4240                 return PTR_ERR(inode);
4241         }
4242
4243         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, lma);
4244         iput(inode);
4245         if (rc != 0)
4246                 fid_zero(&oic->oic_fid);
4247         else
4248                 *fid = oic->oic_fid = lma->lma_self_fid;
4249         return rc;
4250 }
4251
4252 void osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
4253                       struct osd_inode_id *id, const struct lu_fid *fid)
4254 {
4255         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
4256                id->oii_ino, id->oii_gen, info);
4257         info->oti_cache.oic_lid = *id;
4258         info->oti_cache.oic_fid = *fid;
4259         info->oti_cache.oic_dev = osd;
4260 }
4261
4262 /**
4263  * Get parent FID from the linkEA.
4264  *
4265  * For a directory which parent resides on remote MDT, to satisfy the
4266  * local e2fsck, we insert it into the /REMOTE_PARENT_DIR locally. On
4267  * the other hand, to make the lookup(..) on the directory can return
4268  * the real parent FID, we append the real parent FID after its ".."
4269  * name entry in the /REMOTE_PARENT_DIR.
4270  *
4271  * Unfortunately, such PFID-in-dirent cannot be preserved via file-level
4272  * backup. So after the restore, we cannot get the right parent FID from
4273  * its ".." name entry in the /REMOTE_PARENT_DIR. Under such case, since
4274  * we have stored the real parent FID in the directory object's linkEA,
4275  * we can parse the linkEA for the real parent FID.
4276  *
4277  * \param[in] env       pointer to the thread context
4278  * \param[in] obj       pointer to the object to be handled
4279  * \param[out]fid       pointer to the buffer to hold the parent FID
4280  *
4281  * \retval              0 for getting the real parent FID successfully
4282  * \retval              negative error number on failure
4283  */
4284 static int osd_get_pfid_from_linkea(const struct lu_env *env,
4285                                     struct osd_object *obj,
4286                                     struct lu_fid *fid)
4287 {
4288         struct osd_thread_info  *oti    = osd_oti_get(env);
4289         struct lu_buf           *buf    = &oti->oti_big_buf;
4290         struct dentry           *dentry = &oti->oti_obj_dentry;
4291         struct inode            *inode  = obj->oo_inode;
4292         struct linkea_data       ldata  = { NULL };
4293         int                      rc;
4294         ENTRY;
4295
4296         fid_zero(fid);
4297         if (!S_ISDIR(inode->i_mode))
4298                 RETURN(-EIO);
4299
4300 again:
4301         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
4302                              buf->lb_buf, buf->lb_len);
4303         if (rc == -ERANGE) {
4304                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
4305                                      NULL, 0);
4306                 if (rc > 0) {
4307                         lu_buf_realloc(buf, rc);
4308                         if (buf->lb_buf == NULL)
4309                                 RETURN(-ENOMEM);
4310
4311                         goto again;
4312                 }
4313         }
4314
4315         if (unlikely(rc == 0))
4316                 RETURN(-ENODATA);
4317
4318         if (rc < 0)
4319                 RETURN(rc);
4320
4321         if (unlikely(buf->lb_buf == NULL)) {
4322                 lu_buf_realloc(buf, rc);
4323                 if (buf->lb_buf == NULL)
4324                         RETURN(-ENOMEM);
4325
4326                 goto again;
4327         }
4328
4329         ldata.ld_buf = buf;
4330         rc = linkea_init(&ldata);
4331         if (rc == 0) {
4332                 linkea_first_entry(&ldata);
4333                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, NULL, fid);
4334         }
4335
4336         RETURN(rc);
4337 }
4338
4339 /**
4340  * Calls ->lookup() to find dentry. From dentry get inode and
4341  * read inode's ea to get fid. This is required for  interoperability
4342  * mode (b11826)
4343  *
4344  * \retval   0, on success
4345  * \retval -ve, on error
4346  */
4347 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
4348                              struct dt_rec *rec, const struct dt_key *key)
4349 {
4350         struct inode                    *dir    = obj->oo_inode;
4351         struct dentry                   *dentry;
4352         struct ldiskfs_dir_entry_2      *de;
4353         struct buffer_head              *bh;
4354         struct lu_fid                   *fid = (struct lu_fid *) rec;
4355         struct htree_lock               *hlock = NULL;
4356         int                             ino;
4357         int                             rc;
4358         ENTRY;
4359
4360         LASSERT(dir->i_op != NULL);
4361         LASSERT(dir->i_op->lookup != NULL);
4362
4363         dentry = osd_child_dentry_get(env, obj,
4364                                       (char *)key, strlen((char *)key));
4365
4366         if (obj->oo_hl_head != NULL) {
4367                 hlock = osd_oti_get(env)->oti_hlock;
4368                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4369                                    dir, LDISKFS_HLOCK_LOOKUP);
4370         } else {
4371                 down_read(&obj->oo_ext_idx_sem);
4372         }
4373
4374         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
4375         if (bh) {
4376                 struct osd_thread_info *oti = osd_oti_get(env);
4377                 struct osd_inode_id *id = &oti->oti_id;
4378                 struct osd_idmap_cache *oic = &oti->oti_cache;
4379                 struct osd_device *dev = osd_obj2dev(obj);
4380
4381                 ino = le32_to_cpu(de->inode);
4382                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
4383                         brelse(bh);
4384                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
4385                         GOTO(out, rc);
4386                 }
4387
4388                 rc = osd_get_fid_from_dentry(de, rec);
4389
4390                 /* done with de, release bh */
4391                 brelse(bh);
4392                 if (rc != 0) {
4393                         if (unlikely(ino == osd_remote_parent_ino(dev)))
4394                                 /* If the parent is on remote MDT, and there
4395                                  * is no FID-in-dirent, then we have to get
4396                                  * the parent FID from the linkEA.  */
4397                                 rc = osd_get_pfid_from_linkea(env, obj, fid);
4398                         else
4399                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
4400                 } else {
4401                         osd_id_gen(id, ino, OSD_OII_NOGEN);
4402                 }
4403
4404                 if (rc != 0) {
4405                         fid_zero(&oic->oic_fid);
4406                         GOTO(out, rc);
4407                 }
4408
4409                 if (osd_remote_fid(env, dev, fid))
4410                         GOTO(out, rc = 0);
4411
4412                 osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id, fid);
4413                 osd_consistency_check(oti, dev, oic);
4414         } else {
4415                 rc = -ENOENT;
4416         }
4417
4418         GOTO(out, rc);
4419
4420 out:
4421         if (hlock != NULL)
4422                 ldiskfs_htree_unlock(hlock);
4423         else
4424                 up_read(&obj->oo_ext_idx_sem);
4425         return rc;
4426 }
4427
4428 /**
4429  * Find the osd object for given fid.
4430  *
4431  * \param fid need to find the osd object having this fid
4432  *
4433  * \retval osd_object on success
4434  * \retval        -ve on error
4435  */
4436 static struct osd_object *osd_object_find(const struct lu_env *env,
4437                                           struct dt_object *dt,
4438                                           const struct lu_fid *fid)
4439 {
4440         struct lu_device  *ludev = dt->do_lu.lo_dev;
4441         struct osd_object *child = NULL;
4442         struct lu_object  *luch;
4443         struct lu_object  *lo;
4444
4445         /*
4446          * at this point topdev might not exist yet
4447          * (i.e. MGS is preparing profiles). so we can
4448          * not rely on topdev and instead lookup with
4449          * our device passed as topdev. this can't work
4450          * if the object isn't cached yet (as osd doesn't
4451          * allocate lu_header). IOW, the object must be
4452          * in the cache, otherwise lu_object_alloc() crashes
4453          * -bzzz
4454          */
4455         luch = lu_object_find_at(env, ludev->ld_site->ls_top_dev == NULL ?
4456                                  ludev : ludev->ld_site->ls_top_dev,
4457                                  fid, NULL);
4458         if (!IS_ERR(luch)) {
4459                 if (lu_object_exists(luch)) {
4460                         lo = lu_object_locate(luch->lo_header, ludev->ld_type);
4461                         if (lo != NULL)
4462                                 child = osd_obj(lo);
4463                         else
4464                                 LU_OBJECT_DEBUG(D_ERROR, env, luch,
4465                                                 "lu_object can't be located"
4466                                                 DFID"\n", PFID(fid));
4467
4468                         if (child == NULL) {
4469                                 lu_object_put(env, luch);
4470                                 CERROR("Unable to get osd_object\n");
4471                                 child = ERR_PTR(-ENOENT);
4472                         }
4473                 } else {
4474                         LU_OBJECT_DEBUG(D_ERROR, env, luch,
4475                                         "lu_object does not exists "DFID"\n",
4476                                         PFID(fid));
4477                         lu_object_put(env, luch);
4478                         child = ERR_PTR(-ENOENT);
4479                 }
4480         } else {
4481                 child = ERR_CAST(luch);
4482         }
4483
4484         return child;
4485 }
4486
4487 /**
4488  * Put the osd object once done with it.
4489  *
4490  * \param obj osd object that needs to be put
4491  */
4492 static inline void osd_object_put(const struct lu_env *env,
4493                                   struct osd_object *obj)
4494 {
4495         lu_object_put(env, &obj->oo_dt.do_lu);
4496 }
4497
4498 static int osd_index_declare_ea_insert(const struct lu_env *env,
4499                                        struct dt_object *dt,
4500                                        const struct dt_rec *rec,
4501                                        const struct dt_key *key,
4502                                        struct thandle *handle)
4503 {
4504         struct osd_thandle      *oh;
4505         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
4506         struct lu_fid           *fid = (struct lu_fid *)rec;
4507         int                     rc;
4508         ENTRY;
4509
4510         LASSERT(!dt_object_remote(dt));
4511         LASSERT(handle != NULL);
4512
4513         oh = container_of0(handle, struct osd_thandle, ot_super);
4514         LASSERT(oh->ot_handle == NULL);
4515
4516         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4517                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4518
4519         if (osd_dt_obj(dt)->oo_inode != NULL) {
4520                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
4521
4522                 /* We ignore block quota on meta pool (MDTs), so needn't
4523                  * calculate how many blocks will be consumed by this index
4524                  * insert */
4525                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
4526                                            i_gid_read(inode), 0, oh,
4527                                            osd_dt_obj(dt), true, NULL, false);
4528         }
4529
4530         if (fid == NULL)
4531                 RETURN(0);
4532
4533         rc = osd_remote_fid(env, osd, fid);
4534         if (rc <= 0)
4535                 RETURN(rc);
4536
4537         rc = 0;
4538
4539         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
4540                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
4541         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4542                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4543         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4544                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4545
4546         RETURN(rc);
4547 }
4548
4549 /**
4550  * Index add function for interoperability mode (b11826).
4551  * It will add the directory entry.This entry is needed to
4552  * maintain name->fid mapping.
4553  *
4554  * \param key it is key i.e. file entry to be inserted
4555  * \param rec it is value of given key i.e. fid
4556  *
4557  * \retval   0, on success
4558  * \retval -ve, on error
4559  */
4560 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
4561                                const struct dt_rec *rec,
4562                                const struct dt_key *key, struct thandle *th,
4563                                struct lustre_capa *capa, int ignore_quota)
4564 {
4565         struct osd_object       *obj = osd_dt_obj(dt);
4566         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
4567         struct dt_insert_rec    *rec1   = (struct dt_insert_rec *)rec;
4568         const struct lu_fid     *fid    = rec1->rec_fid;
4569         const char              *name = (const char *)key;
4570         struct osd_thread_info  *oti   = osd_oti_get(env);
4571         struct osd_inode_id     *id    = &oti->oti_id;
4572         struct inode            *child_inode = NULL;
4573         struct osd_object       *child = NULL;
4574         int                     rc;
4575         ENTRY;
4576
4577         if (!dt_object_exists(dt))
4578                 RETURN(-ENOENT);
4579
4580         LASSERT(osd_invariant(obj));
4581         LASSERT(!dt_object_remote(dt));
4582         LASSERT(th != NULL);
4583
4584         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4585
4586         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
4587                 RETURN(-EACCES);
4588
4589         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!\n", PFID(fid));
4590
4591         rc = osd_remote_fid(env, osd, fid);
4592         if (rc < 0) {
4593                 CERROR("%s: Can not find object "DFID" rc %d\n",
4594                        osd_name(osd), PFID(fid), rc);
4595                 RETURN(rc);
4596         }
4597
4598         if (rc == 1) {
4599                 /* Insert remote entry */
4600                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
4601                         struct osd_mdobj_map    *omm = osd->od_mdt_map;
4602                         struct osd_thandle      *oh;
4603
4604                         /* If parent on remote MDT, we need put this object
4605                          * under AGENT */
4606                         oh = container_of(th, typeof(*oh), ot_super);
4607                         rc = osd_add_to_remote_parent(env, osd, obj, oh);
4608                         if (rc != 0) {
4609                                 CERROR("%s: add "DFID" error: rc = %d\n",
4610                                        osd_name(osd),
4611                                        PFID(lu_object_fid(&dt->do_lu)), rc);
4612                                 RETURN(rc);
4613                         }
4614
4615                         child_inode = igrab(omm->omm_remote_parent->d_inode);
4616                 } else {
4617                         child_inode = osd_create_local_agent_inode(env, osd,
4618                                         obj, fid, rec1->rec_type & S_IFMT, th);
4619                         if (IS_ERR(child_inode))
4620                                 RETURN(PTR_ERR(child_inode));
4621                 }
4622         } else {
4623                 /* Insert local entry */
4624                 child = osd_object_find(env, dt, fid);
4625                 if (IS_ERR(child)) {
4626                         CERROR("%s: Can not find object "DFID"%u:%u: rc = %d\n",
4627                                osd_name(osd), PFID(fid),
4628                                id->oii_ino, id->oii_gen,
4629                                (int)PTR_ERR(child));
4630                         RETURN(PTR_ERR(child));
4631                 }
4632                 child_inode = igrab(child->oo_inode);
4633         }
4634
4635         rc = osd_ea_add_rec(env, obj, child_inode, name, fid, th);
4636
4637         CDEBUG(D_INODE, "parent %lu insert %s:%lu rc = %d\n",
4638                obj->oo_inode->i_ino, name, child_inode->i_ino, rc);
4639
4640         iput(child_inode);
4641         if (child != NULL)
4642                 osd_object_put(env, child);
4643         LASSERT(osd_invariant(obj));
4644         RETURN(rc);
4645 }
4646
4647 /**
4648  *  Initialize osd Iterator for given osd index object.
4649  *
4650  *  \param  dt      osd index object
4651  */
4652
4653 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
4654                                      struct dt_object *dt,
4655                                      __u32 unused,
4656                                      struct lustre_capa *capa)
4657 {
4658         struct osd_it_iam      *it;
4659         struct osd_object      *obj = osd_dt_obj(dt);
4660         struct lu_object       *lo  = &dt->do_lu;
4661         struct iam_path_descr  *ipd;
4662         struct iam_container   *bag = &obj->oo_dir->od_container;
4663
4664         if (!dt_object_exists(dt))
4665                 return ERR_PTR(-ENOENT);
4666
4667         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
4668                 return ERR_PTR(-EACCES);
4669
4670         OBD_ALLOC_PTR(it);
4671         if (it == NULL)
4672                 return ERR_PTR(-ENOMEM);
4673
4674         ipd = osd_it_ipd_get(env, bag);
4675         if (likely(ipd != NULL)) {
4676                 it->oi_obj = obj;
4677                 it->oi_ipd = ipd;
4678                 lu_object_get(lo);
4679                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
4680                 return (struct dt_it *)it;
4681         } else {
4682                 OBD_FREE_PTR(it);
4683                 return ERR_PTR(-ENOMEM);
4684         }
4685 }
4686
4687 /**
4688  * free given Iterator.
4689  */
4690
4691 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
4692 {
4693         struct osd_it_iam       *it  = (struct osd_it_iam *)di;
4694         struct osd_object       *obj = it->oi_obj;
4695
4696         iam_it_fini(&it->oi_it);
4697         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
4698         lu_object_put(env, &obj->oo_dt.do_lu);
4699         OBD_FREE_PTR(it);
4700 }
4701
4702 /**
4703  *  Move Iterator to record specified by \a key
4704  *
4705  *  \param  di      osd iterator
4706  *  \param  key     key for index
4707  *
4708  *  \retval +ve  di points to record with least key not larger than key
4709  *  \retval  0   di points to exact matched key
4710  *  \retval -ve  failure
4711  */
4712
4713 static int osd_it_iam_get(const struct lu_env *env,
4714                           struct dt_it *di, const struct dt_key *key)
4715 {
4716         struct osd_thread_info  *oti = osd_oti_get(env);
4717         struct osd_it_iam       *it = (struct osd_it_iam *)di;
4718
4719         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4720                 /* swab quota uid/gid */
4721                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4722                 key = (struct dt_key *)&oti->oti_quota_id;
4723         }
4724
4725         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
4726 }
4727
4728 /**
4729  *  Release Iterator
4730  *
4731  *  \param  di      osd iterator
4732  */
4733 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
4734 {
4735         struct osd_it_iam *it = (struct osd_it_iam *)di;
4736
4737         iam_it_put(&it->oi_it);
4738 }
4739
4740 /**
4741  *  Move iterator by one record
4742  *
4743  *  \param  di      osd iterator
4744  *
4745  *  \retval +1   end of container reached
4746  *  \retval  0   success
4747  *  \retval -ve  failure
4748  */
4749
4750 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
4751 {
4752         struct osd_it_iam *it = (struct osd_it_iam *)di;
4753
4754         return iam_it_next(&it->oi_it);
4755 }
4756
4757 /**
4758  * Return pointer to the key under iterator.
4759  */
4760
4761 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
4762                                  const struct dt_it *di)
4763 {
4764         struct osd_thread_info *oti = osd_oti_get(env);
4765         struct osd_it_iam      *it = (struct osd_it_iam *)di;
4766         struct osd_object      *obj = it->oi_obj;
4767         struct dt_key          *key;
4768
4769         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
4770
4771         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
4772                 /* swab quota uid/gid */
4773                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
4774                 key = (struct dt_key *)&oti->oti_quota_id;
4775         }
4776
4777         return key;
4778 }
4779
4780 /**
4781  * Return size of key under iterator (in bytes)
4782  */
4783
4784 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
4785 {
4786         struct osd_it_iam *it = (struct osd_it_iam *)di;
4787
4788         return iam_it_key_size(&it->oi_it);
4789 }
4790
4791 static inline void
4792 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
4793 {
4794         /* check if file type is required */
4795         if (ent->lde_attrs & LUDA_TYPE) {
4796                 struct luda_type *lt;
4797                 int align = sizeof(*lt) - 1;
4798
4799                 len = (len + align) & ~align;
4800                 lt = (struct luda_type *)(ent->lde_name + len);
4801                 lt->lt_type = cpu_to_le16(DTTOIF(type));
4802         }
4803
4804         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
4805 }
4806
4807 /**
4808  * build lu direct from backend fs dirent.
4809  */
4810
4811 static inline void
4812 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
4813                    char *name, __u16 namelen, __u16 type, __u32 attr)
4814 {
4815         ent->lde_attrs = attr | LUDA_FID;
4816         fid_cpu_to_le(&ent->lde_fid, fid);
4817
4818         ent->lde_hash = cpu_to_le64(offset);
4819         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
4820
4821         strncpy(ent->lde_name, name, namelen);
4822         ent->lde_name[namelen] = '\0';
4823         ent->lde_namelen = cpu_to_le16(namelen);
4824
4825         /* append lustre attributes */
4826         osd_it_append_attrs(ent, namelen, type);
4827 }
4828
4829 /**
4830  * Return pointer to the record under iterator.
4831  */
4832 static int osd_it_iam_rec(const struct lu_env *env,
4833                           const struct dt_it *di,
4834                           struct dt_rec *dtrec, __u32 attr)
4835 {
4836         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
4837         struct osd_thread_info *info = osd_oti_get(env);
4838         ENTRY;
4839
4840         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
4841                 const struct osd_fid_pack *rec;
4842                 struct lu_fid             *fid = &info->oti_fid;
4843                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
4844                 char                      *name;
4845                 int                        namelen;
4846                 __u64                      hash;
4847                 int                        rc;
4848
4849                 name = (char *)iam_it_key_get(&it->oi_it);
4850                 if (IS_ERR(name))
4851                         RETURN(PTR_ERR(name));
4852
4853                 namelen = iam_it_key_size(&it->oi_it);
4854
4855                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
4856                 if (IS_ERR(rec))
4857                         RETURN(PTR_ERR(rec));
4858
4859                 rc = osd_fid_unpack(fid, rec);
4860                 if (rc)
4861                         RETURN(rc);
4862
4863                 hash = iam_it_store(&it->oi_it);
4864
4865                 /* IAM does not store object type in IAM index (dir) */
4866                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
4867                                    0, LUDA_FID);
4868         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4869                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4870                            (struct iam_rec *)dtrec);
4871                 osd_quota_unpack(it->oi_obj, dtrec);
4872         } else {
4873                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4874                            (struct iam_rec *)dtrec);
4875         }
4876
4877         RETURN(0);
4878 }
4879
4880 /**
4881  * Returns cookie for current Iterator position.
4882  */
4883 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
4884 {
4885         struct osd_it_iam *it = (struct osd_it_iam *)di;
4886
4887         return iam_it_store(&it->oi_it);
4888 }
4889
4890 /**
4891  * Restore iterator from cookie.
4892  *
4893  * \param  di      osd iterator
4894  * \param  hash    Iterator location cookie
4895  *
4896  * \retval +ve  di points to record with least key not larger than key.
4897  * \retval  0   di points to exact matched key
4898  * \retval -ve  failure
4899  */
4900
4901 static int osd_it_iam_load(const struct lu_env *env,
4902                            const struct dt_it *di, __u64 hash)
4903 {
4904         struct osd_it_iam *it = (struct osd_it_iam *)di;
4905
4906         return iam_it_load(&it->oi_it, hash);
4907 }
4908
4909 static const struct dt_index_operations osd_index_iam_ops = {
4910         .dio_lookup         = osd_index_iam_lookup,
4911         .dio_declare_insert = osd_index_declare_iam_insert,
4912         .dio_insert         = osd_index_iam_insert,
4913         .dio_declare_delete = osd_index_declare_iam_delete,
4914         .dio_delete         = osd_index_iam_delete,
4915         .dio_it     = {
4916                 .init     = osd_it_iam_init,
4917                 .fini     = osd_it_iam_fini,
4918                 .get      = osd_it_iam_get,
4919                 .put      = osd_it_iam_put,
4920                 .next     = osd_it_iam_next,
4921                 .key      = osd_it_iam_key,
4922                 .key_size = osd_it_iam_key_size,
4923                 .rec      = osd_it_iam_rec,
4924                 .store    = osd_it_iam_store,
4925                 .load     = osd_it_iam_load
4926         }
4927 };
4928
4929
4930 /**
4931  * Creates or initializes iterator context.
4932  *
4933  * \retval struct osd_it_ea, iterator structure on success
4934  *
4935  */
4936 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
4937                                     struct dt_object *dt,
4938                                     __u32 attr,
4939                                     struct lustre_capa *capa)
4940 {
4941         struct osd_object       *obj  = osd_dt_obj(dt);
4942         struct osd_thread_info  *info = osd_oti_get(env);
4943         struct osd_it_ea        *oie;
4944         struct file             *file;
4945         struct lu_object        *lo   = &dt->do_lu;
4946         struct dentry           *obj_dentry;
4947         ENTRY;
4948
4949         if (!dt_object_exists(dt))
4950                 RETURN(ERR_PTR(-ENOENT));
4951
4952         OBD_SLAB_ALLOC_PTR_GFP(oie, osd_itea_cachep, GFP_NOFS);
4953         if (oie == NULL)
4954                 RETURN(ERR_PTR(-ENOMEM));
4955         obj_dentry = &oie->oie_dentry;
4956
4957         obj_dentry->d_inode = obj->oo_inode;
4958         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
4959         obj_dentry->d_name.hash = 0;
4960
4961         oie->oie_rd_dirent       = 0;
4962         oie->oie_it_dirent       = 0;
4963         oie->oie_dirent          = NULL;
4964         if (unlikely(!info->oti_it_ea_buf_used)) {
4965                 oie->oie_buf = info->oti_it_ea_buf;
4966                 info->oti_it_ea_buf_used = 1;
4967         } else {
4968                 OBD_ALLOC(oie->oie_buf, OSD_IT_EA_BUFSIZE);
4969                 if (oie->oie_buf == NULL)
4970                         RETURN(ERR_PTR(-ENOMEM));
4971         }
4972         oie->oie_obj             = obj;
4973
4974         file = &oie->oie_file;
4975
4976         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
4977         if (attr & LUDA_64BITHASH)
4978                 file->f_mode    = FMODE_64BITHASH;
4979         else
4980                 file->f_mode    = FMODE_32BITHASH;
4981         file->f_dentry          = obj_dentry;
4982         file->f_mapping         = obj->oo_inode->i_mapping;
4983         file->f_op              = obj->oo_inode->i_fop;
4984         set_file_inode(file, obj->oo_inode);
4985
4986         lu_object_get(lo);
4987         RETURN((struct dt_it *) oie);
4988 }
4989
4990 /**
4991  * Destroy or finishes iterator context.
4992  *
4993  * \param di iterator structure to be destroyed
4994  */
4995 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
4996 {
4997         struct osd_thread_info  *info = osd_oti_get(env);
4998         struct osd_it_ea        *oie    = (struct osd_it_ea *)di;
4999         struct osd_object       *obj    = oie->oie_obj;
5000         struct inode            *inode  = obj->oo_inode;
5001
5002         ENTRY;
5003         oie->oie_file.f_op->release(inode, &oie->oie_file);
5004         lu_object_put(env, &obj->oo_dt.do_lu);
5005         if (unlikely(oie->oie_buf != info->oti_it_ea_buf))
5006                 OBD_FREE(oie->oie_buf, OSD_IT_EA_BUFSIZE);
5007         else
5008                 info->oti_it_ea_buf_used = 0;
5009         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
5010         EXIT;
5011 }
5012
5013 /**
5014  * It position the iterator at given key, so that next lookup continues from
5015  * that key Or it is similar to dio_it->load() but based on a key,
5016  * rather than file position.
5017  *
5018  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
5019  * to the beginning.
5020  *
5021  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
5022  */
5023 static int osd_it_ea_get(const struct lu_env *env,
5024                          struct dt_it *di, const struct dt_key *key)
5025 {
5026         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
5027
5028         ENTRY;
5029         LASSERT(((const char *)key)[0] == '\0');
5030         it->oie_file.f_pos      = 0;
5031         it->oie_rd_dirent       = 0;
5032         it->oie_it_dirent       = 0;
5033         it->oie_dirent          = NULL;
5034
5035         RETURN(+1);
5036 }
5037
5038 /**
5039  * Does nothing
5040  */
5041 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
5042 {
5043 }
5044
5045 struct osd_filldir_cbs {
5046 #ifdef HAVE_DIR_CONTEXT
5047         struct dir_context ctx;
5048 #endif
5049         struct osd_it_ea  *it;
5050 };
5051 /**
5052  * It is called internally by ->readdir(). It fills the
5053  * iterator's in-memory data structure with required
5054  * information i.e. name, namelen, rec_size etc.
5055  *
5056  * \param buf in which information to be filled in.
5057  * \param name name of the file in given dir
5058  *
5059  * \retval 0 on success
5060  * \retval 1 on buffer full
5061  */
5062 static int osd_ldiskfs_filldir(void *buf, const char *name, int namelen,
5063                                loff_t offset, __u64 ino,
5064                                unsigned d_type)
5065 {
5066         struct osd_it_ea        *it   = ((struct osd_filldir_cbs *)buf)->it;
5067         struct osd_object       *obj  = it->oie_obj;
5068         struct osd_it_ea_dirent *ent  = it->oie_dirent;
5069         struct lu_fid           *fid  = &ent->oied_fid;
5070         struct osd_fid_pack     *rec;
5071         ENTRY;
5072
5073         /* this should never happen */
5074         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
5075                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
5076                 RETURN(-EIO);
5077         }
5078
5079         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
5080             OSD_IT_EA_BUFSIZE)
5081                 RETURN(1);
5082
5083         /* "." is just the object itself. */
5084         if (namelen == 1 && name[0] == '.') {
5085                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
5086         } else if (d_type & LDISKFS_DIRENT_LUFID) {
5087                 rec = (struct osd_fid_pack*) (name + namelen + 1);
5088                 if (osd_fid_unpack(fid, rec) != 0)
5089                         fid_zero(fid);
5090         } else {
5091                 fid_zero(fid);
5092         }
5093         d_type &= ~LDISKFS_DIRENT_LUFID;
5094
5095         /* NOT export local root. */
5096         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
5097                 ino = obj->oo_inode->i_ino;
5098                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
5099         }
5100
5101         ent->oied_ino     = ino;
5102         ent->oied_off     = offset;
5103         ent->oied_namelen = namelen;
5104         ent->oied_type    = d_type;
5105
5106         memcpy(ent->oied_name, name, namelen);
5107
5108         it->oie_rd_dirent++;
5109         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
5110         RETURN(0);
5111 }
5112
5113 /**
5114  * Calls ->readdir() to load a directory entry at a time
5115  * and stored it in iterator's in-memory data structure.
5116  *
5117  * \param di iterator's in memory structure
5118  *
5119  * \retval   0 on success
5120  * \retval -ve on error
5121  * \retval +1 reach the end of entry
5122  */
5123 static int osd_ldiskfs_it_fill(const struct lu_env *env,
5124                                const struct dt_it *di)
5125 {
5126         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
5127         struct osd_object  *obj   = it->oie_obj;
5128         struct inode       *inode = obj->oo_inode;
5129         struct htree_lock  *hlock = NULL;
5130         struct file        *filp  = &it->oie_file;
5131         int                 rc = 0;
5132         struct osd_filldir_cbs buf = {
5133 #ifdef HAVE_DIR_CONTEXT
5134                 .ctx.actor = osd_ldiskfs_filldir,
5135 #endif
5136                 .it = it
5137         };
5138
5139         ENTRY;
5140         it->oie_dirent = it->oie_buf;
5141         it->oie_rd_dirent = 0;
5142
5143         if (obj->oo_hl_head != NULL) {
5144                 hlock = osd_oti_get(env)->oti_hlock;
5145                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5146                                    inode, LDISKFS_HLOCK_READDIR);
5147         } else {
5148                 down_read(&obj->oo_ext_idx_sem);
5149         }
5150
5151 #ifdef HAVE_DIR_CONTEXT
5152         buf.ctx.pos = filp->f_pos;
5153         rc = inode->i_fop->iterate(filp, &buf.ctx);
5154         filp->f_pos = buf.ctx.pos;
5155 #else
5156         rc = inode->i_fop->readdir(filp, &buf, osd_ldiskfs_filldir);
5157 #endif
5158
5159         if (hlock != NULL)
5160                 ldiskfs_htree_unlock(hlock);
5161         else
5162                 up_read(&obj->oo_ext_idx_sem);
5163
5164         if (it->oie_rd_dirent == 0) {
5165                 /*If it does not get any dirent, it means it has been reached
5166                  *to the end of the dir */
5167                 it->oie_file.f_pos = ldiskfs_get_htree_eof(&it->oie_file);
5168                 if (rc == 0)
5169                         rc = 1;
5170         } else {
5171                 it->oie_dirent = it->oie_buf;
5172                 it->oie_it_dirent = 1;
5173         }
5174
5175         RETURN(rc);
5176 }
5177
5178 /**
5179  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5180  * to load a directory entry at a time and stored it in
5181  * iterator's in-memory data structure.
5182  *
5183  * \param di iterator's in memory structure
5184  *
5185  * \retval +ve iterator reached to end
5186  * \retval   0 iterator not reached to end
5187  * \retval -ve on error
5188  */
5189 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
5190 {
5191         struct osd_it_ea *it = (struct osd_it_ea *)di;
5192         int rc;
5193
5194         ENTRY;
5195
5196         if (it->oie_it_dirent < it->oie_rd_dirent) {
5197                 it->oie_dirent =
5198                         (void *) it->oie_dirent +
5199                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
5200                                        it->oie_dirent->oied_namelen);
5201                 it->oie_it_dirent++;
5202                 RETURN(0);
5203         } else {
5204                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
5205                         rc = +1;
5206                 else
5207                         rc = osd_ldiskfs_it_fill(env, di);
5208         }
5209
5210         RETURN(rc);
5211 }
5212
5213 /**
5214  * Returns the key at current position from iterator's in memory structure.
5215  *
5216  * \param di iterator's in memory structure
5217  *
5218  * \retval key i.e. struct dt_key on success
5219  */
5220 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
5221                                     const struct dt_it *di)
5222 {
5223         struct osd_it_ea *it = (struct osd_it_ea *)di;
5224
5225         return (struct dt_key *)it->oie_dirent->oied_name;
5226 }
5227
5228 /**
5229  * Returns the key's size at current position from iterator's in memory structure.
5230  *
5231  * \param di iterator's in memory structure
5232  *
5233  * \retval key_size i.e. struct dt_key on success
5234  */
5235 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
5236 {
5237         struct osd_it_ea *it = (struct osd_it_ea *)di;
5238
5239         return it->oie_dirent->oied_namelen;
5240 }
5241
5242 static int
5243 osd_dirent_update(handle_t *jh, struct super_block *sb,
5244                   struct osd_it_ea_dirent *ent, struct lu_fid *fid,
5245                   struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de)
5246 {
5247         struct osd_fid_pack *rec;
5248         int                  rc;
5249         ENTRY;
5250
5251         LASSERT(de->file_type & LDISKFS_DIRENT_LUFID);
5252         LASSERT(de->rec_len >= de->name_len + sizeof(struct osd_fid_pack));
5253
5254         rc = ldiskfs_journal_get_write_access(jh, bh);
5255         if (rc != 0)
5256                 RETURN(rc);
5257
5258         rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
5259         fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
5260         rc = ldiskfs_handle_dirty_metadata(jh, NULL, bh);
5261
5262         RETURN(rc);
5263 }
5264
5265 static inline int
5266 osd_dirent_has_space(__u16 reclen, __u16 namelen, unsigned blocksize)
5267 {
5268         if (ldiskfs_rec_len_from_disk(reclen, blocksize) >=
5269             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
5270                 return 1;
5271         else
5272                 return 0;
5273 }
5274
5275 static inline int
5276 osd_dot_dotdot_has_space(struct ldiskfs_dir_entry_2 *de, int dot_dotdot)
5277 {
5278         LASSERTF(dot_dotdot == 1 || dot_dotdot == 2,
5279                  "dot_dotdot = %d\n", dot_dotdot);
5280
5281         if (LDISKFS_DIR_REC_LEN(de) >=
5282             __LDISKFS_DIR_REC_LEN(dot_dotdot + 1 + sizeof(struct osd_fid_pack)))
5283                 return 1;
5284         else
5285                 return 0;
5286 }
5287
5288 static int
5289 osd_dirent_reinsert(const struct lu_env *env, handle_t *jh,
5290                     struct inode *dir, struct inode *inode,
5291                     struct osd_it_ea_dirent *ent, struct lu_fid *fid,
5292                     struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de,
5293                     struct htree_lock *hlock)
5294 {
5295         struct dentry               *dentry;
5296         struct osd_fid_pack         *rec;
5297         struct ldiskfs_dentry_param *ldp;
5298         int                          rc;
5299         ENTRY;
5300
5301         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
5302                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
5303                 RETURN(0);
5304
5305         /* There is enough space to hold the FID-in-dirent. */
5306         if (osd_dirent_has_space(de->rec_len, ent->oied_namelen,
5307                                  dir->i_sb->s_blocksize)) {
5308                 rc = ldiskfs_journal_get_write_access(jh, bh);
5309                 if (rc != 0)
5310                         RETURN(rc);
5311
5312                 de->name[de->name_len] = 0;
5313                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
5314                 rec->fp_len = sizeof(struct lu_fid) + 1;
5315                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
5316                 de->file_type |= LDISKFS_DIRENT_LUFID;
5317
5318                 rc = ldiskfs_handle_dirty_metadata(jh, NULL, bh);
5319
5320                 RETURN(rc);
5321         }
5322
5323         rc = ldiskfs_delete_entry(jh, dir, de, bh);
5324         if (rc != 0)
5325                 RETURN(rc);
5326
5327         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
5328                                            ent->oied_namelen);
5329         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
5330         osd_get_ldiskfs_dirent_param(ldp, fid);
5331         dentry->d_fsdata = (void *)ldp;
5332         ll_vfs_dq_init(dir);
5333         rc = osd_ldiskfs_add_entry(jh, dentry, inode, hlock);
5334         /* It is too bad, we cannot reinsert the name entry back.
5335          * That means we lose it! */
5336         if (rc != 0)
5337                 CDEBUG(D_LFSCK, "%.16s: fail to reinsert the dirent, "
5338                        "dir = %lu/%u, name = %.*s, "DFID": rc = %d\n",
5339                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5340                        dir->i_ino, dir->i_generation,
5341                        ent->oied_namelen, ent->oied_name, PFID(fid), rc);
5342
5343         RETURN(rc);
5344 }
5345
5346 static int
5347 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
5348                         struct osd_it_ea *it, struct lu_fid *fid,
5349                         struct osd_inode_id *id, __u32 *attr)
5350 {
5351         struct osd_thread_info     *info        = osd_oti_get(env);
5352         struct lustre_mdt_attrs    *lma         = &info->oti_mdt_attrs;
5353         struct osd_device          *dev         = osd_obj2dev(obj);
5354         struct super_block         *sb          = osd_sb(dev);
5355         const char                 *devname     =
5356                                         LDISKFS_SB(sb)->s_es->s_volume_name;
5357         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
5358         struct inode               *dir         = obj->oo_inode;
5359         struct htree_lock          *hlock       = NULL;
5360         struct buffer_head         *bh          = NULL;
5361         handle_t                   *jh          = NULL;
5362         struct ldiskfs_dir_entry_2 *de;
5363         struct dentry              *dentry;
5364         struct inode               *inode;
5365         int                         credits;
5366         int                         rc;
5367         int                         dot_dotdot  = 0;
5368         bool                        dirty       = false;
5369         ENTRY;
5370
5371         if (ent->oied_name[0] == '.') {
5372                 if (ent->oied_namelen == 1)
5373                         dot_dotdot = 1;
5374                 else if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
5375                         dot_dotdot = 2;
5376         }
5377
5378         dentry = osd_child_dentry_get(env, obj, ent->oied_name,
5379                                       ent->oied_namelen);
5380
5381         /* We need to ensure that the name entry is still valid.
5382          * Because it may be removed or renamed by other already.
5383          *
5384          * The unlink or rename operation will start journal before PDO lock,
5385          * so to avoid deadlock, here we need to start journal handle before
5386          * related PDO lock also. But because we do not know whether there
5387          * will be something to be repaired before PDO lock, we just start
5388          * journal without conditions.
5389          *
5390          * We may need to remove the name entry firstly, then insert back.
5391          * One credit is for user quota file update.
5392          * One credit is for group quota file update.
5393          * Two credits are for dirty inode. */
5394         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
5395                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
5396
5397 again:
5398         if (dev->od_dirent_journal != 0) {
5399                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
5400                 if (IS_ERR(jh)) {
5401                         rc = PTR_ERR(jh);
5402                         CDEBUG(D_LFSCK, "%.16s: fail to start trans for dirent "
5403                                "check_repair, dir = %lu/%u, credits = %d, "
5404                                "name = %.*s: rc = %d\n",
5405                                devname, dir->i_ino, dir->i_generation, credits,
5406                                ent->oied_namelen, ent->oied_name, rc);
5407                         RETURN(rc);
5408                 }
5409
5410                 if (obj->oo_hl_head != NULL) {
5411                         hlock = osd_oti_get(env)->oti_hlock;
5412                         /* "0" means exclusive lock for the whole directory.
5413                          * We need to prevent others access such name entry
5414                          * during the delete + insert. Neither HLOCK_ADD nor
5415                          * HLOCK_DEL cannot guarantee the atomicity. */
5416                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
5417                 } else {
5418                         down_write(&obj->oo_ext_idx_sem);
5419                 }
5420         } else {
5421                 if (obj->oo_hl_head != NULL) {
5422                         hlock = osd_oti_get(env)->oti_hlock;
5423                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
5424                                            LDISKFS_HLOCK_LOOKUP);
5425                 } else {
5426                         down_read(&obj->oo_ext_idx_sem);
5427                 }
5428         }
5429
5430         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5431         /* For dot/dotdot entry, if there is not enough space to hold the
5432          * FID-in-dirent, just keep them there. It only happens when the
5433          * device upgraded from 1.8 or restored from MDT file-level backup.
5434          * For the whole directory, only dot/dotdot entry have no FID-in-dirent
5435          * and needs to get FID from LMA when readdir, it will not affect the
5436          * performance much. */
5437         if ((bh == NULL) || (le32_to_cpu(de->inode) != ent->oied_ino) ||
5438             (dot_dotdot != 0 && !osd_dot_dotdot_has_space(de, dot_dotdot))) {
5439                 *attr |= LUDA_IGNORE;
5440                 GOTO(out_journal, rc = 0);
5441         }
5442
5443         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
5444         inode = osd_iget(info, dev, id);
5445         if (IS_ERR(inode)) {
5446                 rc = PTR_ERR(inode);
5447                 if (rc == -ENOENT || rc == -ESTALE)
5448                         rc = 1;
5449                 else
5450                         CDEBUG(D_LFSCK, "%.16s: fail to iget for dirent "
5451                                "check_repair, dir = %lu/%u, name = %.*s: "
5452                                "rc = %d\n",
5453                                devname, dir->i_ino, dir->i_generation,
5454                                ent->oied_namelen, ent->oied_name, rc);
5455
5456                 GOTO(out_journal, rc);
5457         }
5458
5459         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
5460         if (rc == 0) {
5461                 LASSERT(!(lma->lma_compat & LMAC_NOT_IN_OI));
5462
5463                 if (fid_is_sane(fid)) {
5464                         /* FID-in-dirent is valid. */
5465                         if (lu_fid_eq(fid, &lma->lma_self_fid))
5466                                 GOTO(out_inode, rc = 0);
5467
5468                         /* Do not repair under dryrun mode. */
5469                         if (*attr & LUDA_VERIFY_DRYRUN) {
5470                                 *attr |= LUDA_REPAIR;
5471                                 GOTO(out_inode, rc = 0);
5472                         }
5473
5474                         if (dev->od_dirent_journal == 0) {
5475                                 iput(inode);
5476                                 brelse(bh);
5477                                 if (hlock != NULL)
5478                                         ldiskfs_htree_unlock(hlock);
5479                                 else
5480                                         up_read(&obj->oo_ext_idx_sem);
5481                                 dev->od_dirent_journal = 1;
5482                                 goto again;
5483                         }
5484
5485                         *fid = lma->lma_self_fid;
5486                         dirty = true;
5487                         /* Update the FID-in-dirent. */
5488                         rc = osd_dirent_update(jh, sb, ent, fid, bh, de);
5489                         if (rc == 0)
5490                                 *attr |= LUDA_REPAIR;
5491                         else
5492                                 CDEBUG(D_LFSCK, "%.16s: fail to update FID "
5493                                        "in the dirent, dir = %lu/%u, "
5494                                        "name = %.*s, "DFID": rc = %d\n",
5495                                        devname, dir->i_ino, dir->i_generation,
5496                                        ent->oied_namelen, ent->oied_name,
5497                                        PFID(fid), rc);
5498                 } else {
5499                         /* Do not repair under dryrun mode. */
5500                         if (*attr & LUDA_VERIFY_DRYRUN) {
5501                                 *fid = lma->lma_self_fid;
5502                                 *attr |= LUDA_REPAIR;
5503                                 GOTO(out_inode, rc = 0);
5504                         }
5505
5506                         if (dev->od_dirent_journal == 0) {
5507                                 iput(inode);
5508                                 brelse(bh);
5509                                 if (hlock != NULL)
5510                                         ldiskfs_htree_unlock(hlock);
5511                                 else
5512                                         up_read(&obj->oo_ext_idx_sem);
5513                                 dev->od_dirent_journal = 1;
5514                                 goto again;
5515                         }
5516
5517                         *fid = lma->lma_self_fid;
5518                         dirty = true;
5519                         /* Append the FID-in-dirent. */
5520                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5521                                                  fid, bh, de, hlock);
5522                         if (rc == 0)
5523                                 *attr |= LUDA_REPAIR;
5524                         else
5525                                 CDEBUG(D_LFSCK, "%.16s: fail to append FID "
5526                                        "after the dirent, dir = %lu/%u, "
5527                                        "name = %.*s, "DFID": rc = %d\n",
5528                                        devname, dir->i_ino, dir->i_generation,
5529                                        ent->oied_namelen, ent->oied_name,
5530                                        PFID(fid), rc);
5531                 }
5532         } else if (rc == -ENODATA) {
5533                 /* Do not repair under dryrun mode. */
5534                 if (*attr & LUDA_VERIFY_DRYRUN) {
5535                         if (fid_is_sane(fid)) {
5536                                 *attr |= LUDA_REPAIR;
5537                         } else {
5538                                 lu_igif_build(fid, inode->i_ino,
5539                                               inode->i_generation);
5540                                 *attr |= LUDA_UPGRADE;
5541                         }
5542                         GOTO(out_inode, rc = 0);
5543                 }
5544
5545                 if (dev->od_dirent_journal == 0) {
5546                         iput(inode);
5547                         brelse(bh);
5548                         if (hlock != NULL)
5549                                 ldiskfs_htree_unlock(hlock);
5550                         else
5551                                 up_read(&obj->oo_ext_idx_sem);
5552                         dev->od_dirent_journal = 1;
5553                         goto again;
5554                 }
5555
5556                 dirty = true;
5557                 if (unlikely(fid_is_sane(fid))) {
5558                         /* FID-in-dirent exists, but FID-in-LMA is lost.
5559                          * Trust the FID-in-dirent, and add FID-in-LMA. */
5560                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
5561                         if (rc == 0)
5562                                 *attr |= LUDA_REPAIR;
5563                         else
5564                                 CDEBUG(D_LFSCK, "%.16s: fail to set LMA for "
5565                                        "update dirent, dir = %lu/%u, "
5566                                        "name = %.*s, "DFID": rc = %d\n",
5567                                        devname, dir->i_ino, dir->i_generation,
5568                                        ent->oied_namelen, ent->oied_name,
5569                                        PFID(fid), rc);
5570                 } else {
5571                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
5572                         /* It is probably IGIF object. Only aappend the
5573                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
5574                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5575                                                  fid, bh, de, hlock);
5576                         if (rc == 0)
5577                                 *attr |= LUDA_UPGRADE;
5578                         else
5579                                 CDEBUG(D_LFSCK, "%.16s: fail to append IGIF "
5580                                        "after the dirent, dir = %lu/%u, "
5581                                        "name = %.*s, "DFID": rc = %d\n",
5582                                        devname, dir->i_ino, dir->i_generation,
5583                                        ent->oied_namelen, ent->oied_name,
5584                                        PFID(fid), rc);
5585                 }
5586         }
5587
5588         GOTO(out_inode, rc);
5589
5590 out_inode:
5591         iput(inode);
5592
5593 out_journal:
5594         brelse(bh);
5595         if (hlock != NULL) {
5596                 ldiskfs_htree_unlock(hlock);
5597         } else {
5598                 if (dev->od_dirent_journal != 0)
5599                         up_write(&obj->oo_ext_idx_sem);
5600                 else
5601                         up_read(&obj->oo_ext_idx_sem);
5602         }
5603         if (jh != NULL)
5604                 ldiskfs_journal_stop(jh);
5605         if (rc >= 0 && !dirty)
5606                 dev->od_dirent_journal = 0;
5607         return rc;
5608 }
5609
5610 /**
5611  * Returns the value at current position from iterator's in memory structure.
5612  *
5613  * \param di struct osd_it_ea, iterator's in memory structure
5614  * \param attr attr requested for dirent.
5615  * \param lde lustre dirent
5616  *
5617  * \retval   0 no error and \param lde has correct lustre dirent.
5618  * \retval -ve on error
5619  */
5620 static inline int osd_it_ea_rec(const struct lu_env *env,
5621                                 const struct dt_it *di,
5622                                 struct dt_rec *dtrec, __u32 attr)
5623 {
5624         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
5625         struct osd_object      *obj   = it->oie_obj;
5626         struct osd_device      *dev   = osd_obj2dev(obj);
5627         struct osd_thread_info *oti   = osd_oti_get(env);
5628         struct osd_inode_id    *id    = &oti->oti_id;
5629         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
5630         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
5631         __u32                   ino   = it->oie_dirent->oied_ino;
5632         int                     rc    = 0;
5633         ENTRY;
5634
5635         LASSERT(obj->oo_inode != dev->od_mdt_map->omm_remote_parent->d_inode);
5636
5637         if (attr & LUDA_VERIFY) {
5638                 if (unlikely(ino == osd_remote_parent_ino(dev))) {
5639                         attr |= LUDA_IGNORE;
5640                         /* If the parent is on remote MDT, and there
5641                          * is no FID-in-dirent, then we have to get
5642                          * the parent FID from the linkEA.  */
5643                         osd_get_pfid_from_linkea(env, obj, fid);
5644                 } else {
5645                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
5646                                                      &attr);
5647                 }
5648         } else {
5649                 attr &= ~LU_DIRENT_ATTRS_MASK;
5650                 if (!fid_is_sane(fid)) {
5651                         if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP) &&
5652                             likely(it->oie_dirent->oied_namelen != 2 ||
5653                                    it->oie_dirent->oied_name[0] != '.' ||
5654                                    it->oie_dirent->oied_name[1] != '.'))
5655                                 RETURN(-ENOENT);
5656
5657                         if (unlikely(ino == osd_remote_parent_ino(dev)))
5658                                 /* If the parent is on remote MDT, and there
5659                                  * is no FID-in-dirent, then we have to get
5660                                  * the parent FID from the linkEA.  */
5661                                 rc = osd_get_pfid_from_linkea(env, obj, fid);
5662                         else
5663                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
5664                 } else {
5665                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5666                 }
5667         }
5668
5669         /* Pack the entry anyway, at least the offset is right. */
5670         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
5671                            it->oie_dirent->oied_name,
5672                            it->oie_dirent->oied_namelen,
5673                            it->oie_dirent->oied_type, attr);
5674
5675         if (rc < 0)
5676                 RETURN(rc);
5677
5678         if (osd_remote_fid(env, dev, fid))
5679                 RETURN(0);
5680
5681         if (likely(!(attr & LUDA_IGNORE) && rc == 0))
5682                 osd_add_oi_cache(oti, dev, id, fid);
5683
5684         RETURN(rc > 0 ? 0 : rc);
5685 }
5686
5687 /**
5688  * Returns the record size size at current position.
5689  *
5690  * This function will return record(lu_dirent) size in bytes.
5691  *
5692  * \param[in] env       execution environment
5693  * \param[in] di        iterator's in memory structure
5694  * \param[in] attr      attribute of the entry, only requires LUDA_TYPE to
5695  *                      calculate the lu_dirent size.
5696  *
5697  * \retval      record size(in bytes & in memory) of the current lu_dirent
5698  *              entry.
5699  */
5700 static int osd_it_ea_rec_size(const struct lu_env *env, const struct dt_it *di,
5701                               __u32 attr)
5702 {
5703         struct osd_it_ea *it = (struct osd_it_ea *)di;
5704
5705         return lu_dirent_calc_size(it->oie_dirent->oied_namelen, attr);
5706 }
5707
5708 /**
5709  * Returns a cookie for current position of the iterator head, so that
5710  * user can use this cookie to load/start the iterator next time.
5711  *
5712  * \param di iterator's in memory structure
5713  *
5714  * \retval cookie for current position, on success
5715  */
5716 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
5717 {
5718         struct osd_it_ea *it = (struct osd_it_ea *)di;
5719
5720         return it->oie_dirent->oied_off;
5721 }
5722
5723 /**
5724  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5725  * to load a directory entry at a time and stored it i inn,
5726  * in iterator's in-memory data structure.
5727  *
5728  * \param di struct osd_it_ea, iterator's in memory structure
5729  *
5730  * \retval +ve on success
5731  * \retval -ve on error
5732  */
5733 static int osd_it_ea_load(const struct lu_env *env,
5734                           const struct dt_it *di, __u64 hash)
5735 {
5736         struct osd_it_ea *it = (struct osd_it_ea *)di;
5737         int rc;
5738
5739         ENTRY;
5740         it->oie_file.f_pos = hash;
5741
5742         rc =  osd_ldiskfs_it_fill(env, di);
5743         if (rc > 0)
5744                 rc = -ENODATA;
5745
5746         if (rc == 0)
5747                 rc = +1;
5748
5749         RETURN(rc);
5750 }
5751
5752 /**
5753  * Index lookup function for interoperability mode (b11826).
5754  *
5755  * \param key,  key i.e. file name to be searched
5756  *
5757  * \retval +ve, on success
5758  * \retval -ve, on error
5759  */
5760 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
5761                                struct dt_rec *rec, const struct dt_key *key,
5762                                struct lustre_capa *capa)
5763 {
5764         struct osd_object *obj = osd_dt_obj(dt);
5765         int rc = 0;
5766
5767         ENTRY;
5768
5769         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
5770         LINVRNT(osd_invariant(obj));
5771
5772         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
5773                 return -EACCES;
5774
5775         rc = osd_ea_lookup_rec(env, obj, rec, key);
5776         if (rc == 0)
5777                 rc = +1;
5778         RETURN(rc);
5779 }
5780
5781 /**
5782  * Index and Iterator operations for interoperability
5783  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
5784  */
5785 static const struct dt_index_operations osd_index_ea_ops = {
5786         .dio_lookup         = osd_index_ea_lookup,
5787         .dio_declare_insert = osd_index_declare_ea_insert,
5788         .dio_insert         = osd_index_ea_insert,
5789         .dio_declare_delete = osd_index_declare_ea_delete,
5790         .dio_delete         = osd_index_ea_delete,
5791         .dio_it     = {
5792                 .init     = osd_it_ea_init,
5793                 .fini     = osd_it_ea_fini,
5794                 .get      = osd_it_ea_get,
5795                 .put      = osd_it_ea_put,
5796                 .next     = osd_it_ea_next,
5797                 .key      = osd_it_ea_key,
5798                 .key_size = osd_it_ea_key_size,
5799                 .rec      = osd_it_ea_rec,
5800                 .rec_size = osd_it_ea_rec_size,
5801                 .store    = osd_it_ea_store,
5802                 .load     = osd_it_ea_load
5803         }
5804 };
5805
5806 static void *osd_key_init(const struct lu_context *ctx,
5807                           struct lu_context_key *key)
5808 {
5809         struct osd_thread_info *info;
5810
5811         OBD_ALLOC_PTR(info);
5812         if (info == NULL)
5813                 return ERR_PTR(-ENOMEM);
5814
5815         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5816         if (info->oti_it_ea_buf == NULL)
5817                 goto out_free_info;
5818
5819         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
5820
5821         info->oti_hlock = ldiskfs_htree_lock_alloc();
5822         if (info->oti_hlock == NULL)
5823                 goto out_free_ea;
5824
5825         return info;
5826
5827  out_free_ea:
5828         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5829  out_free_info:
5830         OBD_FREE_PTR(info);
5831         return ERR_PTR(-ENOMEM);
5832 }
5833
5834 static void osd_key_fini(const struct lu_context *ctx,
5835                          struct lu_context_key *key, void* data)
5836 {
5837         struct osd_thread_info *info = data;
5838
5839         if (info->oti_hlock != NULL)
5840                 ldiskfs_htree_lock_free(info->oti_hlock);
5841         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5842         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
5843         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
5844         lu_buf_free(&info->oti_big_buf);
5845         OBD_FREE_PTR(info);
5846 }
5847
5848 static void osd_key_exit(const struct lu_context *ctx,
5849                          struct lu_context_key *key, void *data)
5850 {
5851         struct osd_thread_info *info = data;
5852
5853         LASSERT(info->oti_r_locks == 0);
5854         LASSERT(info->oti_w_locks == 0);
5855         LASSERT(info->oti_txns    == 0);
5856 }
5857
5858 /* type constructor/destructor: osd_type_init, osd_type_fini */
5859 LU_TYPE_INIT_FINI(osd, &osd_key);
5860
5861 struct lu_context_key osd_key = {
5862         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
5863         .lct_init = osd_key_init,
5864         .lct_fini = osd_key_fini,
5865         .lct_exit = osd_key_exit
5866 };
5867
5868
5869 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
5870                            const char *name, struct lu_device *next)
5871 {
5872         struct osd_device *osd = osd_dev(d);
5873
5874         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
5875             >= sizeof(osd->od_svname))
5876                 return -E2BIG;
5877         return osd_procfs_init(osd, name);
5878 }
5879
5880 static int osd_fid_init(const struct lu_env *env, struct osd_device *osd)
5881 {
5882         struct seq_server_site  *ss = osd_seq_site(osd);
5883         int                     rc;
5884         ENTRY;
5885
5886         if (osd->od_is_ost || osd->od_cl_seq != NULL)
5887                 RETURN(0);
5888
5889         if (unlikely(ss == NULL))
5890                 RETURN(-ENODEV);
5891
5892         OBD_ALLOC_PTR(osd->od_cl_seq);
5893         if (osd->od_cl_seq == NULL)
5894                 RETURN(-ENOMEM);
5895
5896         rc = seq_client_init(osd->od_cl_seq, NULL, LUSTRE_SEQ_METADATA,
5897                              osd->od_svname, ss->ss_server_seq);
5898
5899         if (rc != 0) {
5900                 OBD_FREE_PTR(osd->od_cl_seq);
5901                 osd->od_cl_seq = NULL;
5902         }
5903
5904         RETURN(rc);
5905 }
5906
5907 static void osd_fid_fini(const struct lu_env *env, struct osd_device *osd)
5908 {
5909         if (osd->od_cl_seq == NULL)
5910                 return;
5911
5912         seq_client_fini(osd->od_cl_seq);
5913         OBD_FREE_PTR(osd->od_cl_seq);
5914         osd->od_cl_seq = NULL;
5915 }
5916
5917 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
5918 {
5919         ENTRY;
5920
5921         /* shutdown quota slave instance associated with the device */
5922         if (o->od_quota_slave != NULL) {
5923                 qsd_fini(env, o->od_quota_slave);
5924                 o->od_quota_slave = NULL;
5925         }
5926
5927         osd_fid_fini(env, o);
5928
5929         RETURN(0);
5930 }
5931
5932 static void osd_umount(const struct lu_env *env, struct osd_device *o)
5933 {
5934         ENTRY;
5935
5936         if (o->od_mnt != NULL) {
5937                 shrink_dcache_sb(osd_sb(o));
5938                 osd_sync(env, &o->od_dt_dev);
5939
5940                 mntput(o->od_mnt);
5941                 o->od_mnt = NULL;
5942         }
5943
5944         EXIT;
5945 }
5946
5947 static int osd_mount(const struct lu_env *env,
5948                      struct osd_device *o, struct lustre_cfg *cfg)
5949 {
5950         const char              *name  = lustre_cfg_string(cfg, 0);
5951         const char              *dev  = lustre_cfg_string(cfg, 1);
5952         const char              *opts;
5953         unsigned long            page, s_flags, lmd_flags = 0;
5954         struct page             *__page;
5955         struct file_system_type *type;
5956         char                    *options = NULL;
5957         char                    *str;
5958         struct osd_thread_info  *info = osd_oti_get(env);
5959         struct lu_fid           *fid = &info->oti_fid;
5960         struct inode            *inode;
5961         int                      rc = 0;
5962         ENTRY;
5963
5964         if (o->od_mnt != NULL)
5965                 RETURN(0);
5966
5967         if (strlen(dev) >= sizeof(o->od_mntdev))
5968                 RETURN(-E2BIG);
5969         strcpy(o->od_mntdev, dev);
5970
5971         OBD_PAGE_ALLOC(__page, GFP_IOFS);
5972         if (__page == NULL)
5973                 GOTO(out, rc = -ENOMEM);
5974
5975         str = lustre_cfg_string(cfg, 2);
5976         s_flags = simple_strtoul(str, NULL, 0);
5977         str = strstr(str, ":");
5978         if (str)
5979                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
5980         opts = lustre_cfg_string(cfg, 3);
5981         page = (unsigned long)page_address(__page);
5982         options = (char *)page;
5983         *options = '\0';
5984         if (opts == NULL)
5985                 strcat(options, "user_xattr,acl");
5986         else
5987                 strcat(options, opts);
5988
5989         /* Glom up mount options */
5990         if (*options != '\0')
5991                 strcat(options, ",");
5992         strlcat(options, "no_mbcache", PAGE_CACHE_SIZE);
5993
5994         type = get_fs_type("ldiskfs");
5995         if (!type) {
5996                 CERROR("%s: cannot find ldiskfs module\n", name);
5997                 GOTO(out, rc = -ENODEV);
5998         }
5999
6000         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
6001         module_put(type->owner);
6002
6003         if (IS_ERR(o->od_mnt)) {
6004                 rc = PTR_ERR(o->od_mnt);
6005                 o->od_mnt = NULL;
6006                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
6007                 GOTO(out, rc);
6008         }
6009
6010 #ifdef HAVE_DEV_SET_RDONLY
6011         if (dev_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
6012                 CERROR("%s: underlying device %s is marked as read-only. "
6013                        "Setup failed\n", name, dev);
6014                 GOTO(out_mnt, rc = -EROFS);
6015         }
6016 #endif
6017
6018         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
6019                                         LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
6020                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
6021                 GOTO(out_mnt, rc = -EINVAL);
6022         }
6023
6024 #ifdef LDISKFS_MOUNT_DIRDATA
6025         if (LDISKFS_HAS_INCOMPAT_FEATURE(o->od_mnt->mnt_sb,
6026                                          LDISKFS_FEATURE_INCOMPAT_DIRDATA))
6027                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
6028         else if (!o->od_is_ost)
6029                 CWARN("%s: device %s was upgraded from Lustre-1.x without "
6030                       "enabling the dirdata feature. If you do not want to "
6031                       "downgrade to Lustre-1.x again, you can enable it via "
6032                       "'tune2fs -O dirdata device'\n", name, dev);
6033 #endif
6034         inode = osd_sb(o)->s_root->d_inode;
6035         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
6036         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
6037         if (rc != 0) {
6038                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
6039                 GOTO(out_mnt, rc);
6040         }
6041
6042         if (lmd_flags & LMD_FLG_NOSCRUB)
6043                 o->od_noscrub = 1;
6044
6045         GOTO(out, rc = 0);
6046
6047 out_mnt:
6048         mntput(o->od_mnt);
6049         o->od_mnt = NULL;
6050
6051 out:
6052         if (__page)
6053                 OBD_PAGE_FREE(__page);
6054
6055         return rc;
6056 }
6057
6058 static struct lu_device *osd_device_fini(const struct lu_env *env,
6059                                          struct lu_device *d)
6060 {
6061         struct osd_device *o = osd_dev(d);
6062         ENTRY;
6063
6064         osd_shutdown(env, o);
6065         osd_procfs_fini(o);
6066         osd_scrub_cleanup(env, o);
6067         osd_obj_map_fini(o);
6068         osd_umount(env, o);
6069
6070         RETURN(NULL);
6071 }
6072
6073 static int osd_device_init0(const struct lu_env *env,
6074                             struct osd_device *o,
6075                             struct lustre_cfg *cfg)
6076 {
6077         struct lu_device        *l = osd2lu_dev(o);
6078         struct osd_thread_info *info;
6079         int                     rc;
6080         int                     cplen = 0;
6081
6082         /* if the module was re-loaded, env can loose its keys */
6083         rc = lu_env_refill((struct lu_env *) env);
6084         if (rc)
6085                 GOTO(out, rc);
6086         info = osd_oti_get(env);
6087         LASSERT(info);
6088
6089         l->ld_ops = &osd_lu_ops;
6090         o->od_dt_dev.dd_ops = &osd_dt_ops;
6091
6092         spin_lock_init(&o->od_osfs_lock);
6093         mutex_init(&o->od_otable_mutex);
6094
6095         o->od_capa_hash = init_capa_hash();
6096         if (o->od_capa_hash == NULL)
6097                 GOTO(out, rc = -ENOMEM);
6098
6099         o->od_read_cache = 1;
6100         o->od_writethrough_cache = 1;
6101         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
6102
6103         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
6104                         sizeof(o->od_svname));
6105         if (cplen >= sizeof(o->od_svname)) {
6106                 rc = -E2BIG;
6107                 GOTO(out_capa, rc);
6108         }
6109
6110         if (server_name_is_ost(o->od_svname))
6111                 o->od_is_ost = 1;
6112
6113         o->od_full_scrub_ratio = OFSR_DEFAULT;
6114         o->od_full_scrub_threshold_rate = FULL_SCRUB_THRESHOLD_RATE_DEFAULT;
6115         rc = osd_mount(env, o, cfg);
6116         if (rc != 0)
6117                 GOTO(out_capa, rc);
6118
6119         rc = osd_obj_map_init(env, o);
6120         if (rc != 0)
6121                 GOTO(out_mnt, rc);
6122
6123         rc = lu_site_init(&o->od_site, l);
6124         if (rc != 0)
6125                 GOTO(out_compat, rc);
6126         o->od_site.ls_bottom_dev = l;
6127
6128         rc = lu_site_init_finish(&o->od_site);
6129         if (rc != 0)
6130                 GOTO(out_site, rc);
6131
6132         /* self-repair LMA by default */
6133         o->od_lma_self_repair = 1;
6134
6135         INIT_LIST_HEAD(&o->od_ios_list);
6136         /* setup scrub, including OI files initialization */
6137         rc = osd_scrub_setup(env, o);
6138         if (rc < 0)
6139                 GOTO(out_site, rc);
6140
6141         rc = osd_procfs_init(o, o->od_svname);
6142         if (rc != 0) {
6143                 CERROR("%s: can't initialize procfs: rc = %d\n",
6144                        o->od_svname, rc);
6145                 GOTO(out_scrub, rc);
6146         }
6147
6148         LASSERT(l->ld_site->ls_linkage.next != NULL);
6149         LASSERT(l->ld_site->ls_linkage.prev != NULL);
6150
6151         /* initialize quota slave instance */
6152         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
6153                                      o->od_proc_entry);
6154         if (IS_ERR(o->od_quota_slave)) {
6155                 rc = PTR_ERR(o->od_quota_slave);
6156                 o->od_quota_slave = NULL;
6157                 GOTO(out_procfs, rc);
6158         }
6159
6160         RETURN(0);
6161
6162 out_procfs:
6163         osd_procfs_fini(o);
6164 out_scrub:
6165         osd_scrub_cleanup(env, o);
6166 out_site:
6167         lu_site_fini(&o->od_site);
6168 out_compat:
6169         osd_obj_map_fini(o);
6170 out_mnt:
6171         osd_umount(env, o);
6172 out_capa:
6173         cleanup_capa_hash(o->od_capa_hash);
6174 out:
6175         return rc;
6176 }
6177
6178 static struct lu_device *osd_device_alloc(const struct lu_env *env,
6179                                           struct lu_device_type *t,
6180                                           struct lustre_cfg *cfg)
6181 {
6182         struct osd_device *o;
6183         int                rc;
6184
6185         OBD_ALLOC_PTR(o);
6186         if (o == NULL)
6187                 return ERR_PTR(-ENOMEM);
6188
6189         rc = dt_device_init(&o->od_dt_dev, t);
6190         if (rc == 0) {
6191                 /* Because the ctx might be revived in dt_device_init,
6192                  * refill the env here */
6193                 lu_env_refill((struct lu_env *)env);
6194                 rc = osd_device_init0(env, o, cfg);
6195                 if (rc)
6196                         dt_device_fini(&o->od_dt_dev);
6197         }
6198
6199         if (unlikely(rc != 0))
6200                 OBD_FREE_PTR(o);
6201
6202         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
6203 }
6204
6205 static struct lu_device *osd_device_free(const struct lu_env *env,
6206                                          struct lu_device *d)
6207 {
6208         struct osd_device *o = osd_dev(d);
6209         ENTRY;
6210
6211         cleanup_capa_hash(o->od_capa_hash);
6212         /* XXX: make osd top device in order to release reference */
6213         d->ld_site->ls_top_dev = d;
6214         lu_site_purge(env, d->ld_site, -1);
6215         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
6216                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
6217                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
6218         }
6219         lu_site_fini(&o->od_site);
6220         dt_device_fini(&o->od_dt_dev);
6221         OBD_FREE_PTR(o);
6222         RETURN(NULL);
6223 }
6224
6225 static int osd_process_config(const struct lu_env *env,
6226                               struct lu_device *d, struct lustre_cfg *cfg)
6227 {
6228         struct osd_device               *o = osd_dev(d);
6229         int                             rc;
6230         ENTRY;
6231
6232         switch (cfg->lcfg_command) {
6233         case LCFG_SETUP:
6234                 rc = osd_mount(env, o, cfg);
6235                 break;
6236         case LCFG_CLEANUP:
6237                 lu_dev_del_linkage(d->ld_site, d);
6238                 rc = osd_shutdown(env, o);
6239                 break;
6240         case LCFG_PARAM:
6241                 LASSERT(&o->od_dt_dev);
6242                 rc = class_process_proc_param(PARAM_OSD, lprocfs_osd_obd_vars,
6243                                               cfg, &o->od_dt_dev);
6244                 if (rc > 0 || rc == -ENOSYS)
6245                         rc = class_process_proc_param(PARAM_OST,
6246                                                       lprocfs_osd_obd_vars,
6247                                                       cfg, &o->od_dt_dev);
6248                 break;
6249         default:
6250                 rc = -ENOSYS;
6251         }
6252
6253         RETURN(rc);
6254 }
6255
6256 static int osd_recovery_complete(const struct lu_env *env,
6257                                  struct lu_device *d)
6258 {
6259         struct osd_device       *osd = osd_dev(d);
6260         int                      rc = 0;
6261         ENTRY;
6262
6263         if (osd->od_quota_slave == NULL)
6264                 RETURN(0);
6265
6266         /* start qsd instance on recovery completion, this notifies the quota
6267          * slave code that we are about to process new requests now */
6268         rc = qsd_start(env, osd->od_quota_slave);
6269         RETURN(rc);
6270 }
6271
6272 /*
6273  * we use exports to track all osd users
6274  */
6275 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
6276                            struct obd_device *obd, struct obd_uuid *cluuid,
6277                            struct obd_connect_data *data, void *localdata)
6278 {
6279         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
6280         struct lustre_handle  conn;
6281         int                   rc;
6282         ENTRY;
6283
6284         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
6285
6286         rc = class_connect(&conn, obd, cluuid);
6287         if (rc)
6288                 RETURN(rc);
6289
6290         *exp = class_conn2export(&conn);
6291
6292         spin_lock(&osd->od_osfs_lock);
6293         osd->od_connects++;
6294         spin_unlock(&osd->od_osfs_lock);
6295
6296         RETURN(0);
6297 }
6298
6299 /*
6300  * once last export (we don't count self-export) disappeared
6301  * osd can be released
6302  */
6303 static int osd_obd_disconnect(struct obd_export *exp)
6304 {
6305         struct obd_device *obd = exp->exp_obd;
6306         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
6307         int                rc, release = 0;
6308         ENTRY;
6309
6310         /* Only disconnect the underlying layers on the final disconnect. */
6311         spin_lock(&osd->od_osfs_lock);
6312         osd->od_connects--;
6313         if (osd->od_connects == 0)
6314                 release = 1;
6315         spin_unlock(&osd->od_osfs_lock);
6316
6317         rc = class_disconnect(exp); /* bz 9811 */
6318
6319         if (rc == 0 && release)
6320                 class_manual_cleanup(obd);
6321         RETURN(rc);
6322 }
6323
6324 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
6325                        struct lu_device *dev)
6326 {
6327         struct osd_device *osd = osd_dev(dev);
6328         int                result = 0;
6329         ENTRY;
6330
6331         if (osd->od_quota_slave != NULL) {
6332                 /* set up quota slave objects */
6333                 result = qsd_prepare(env, osd->od_quota_slave);
6334                 if (result != 0)
6335                         RETURN(result);
6336         }
6337
6338         result = osd_fid_init(env, osd);
6339
6340         RETURN(result);
6341 }
6342
6343 static int osd_fid_alloc(const struct lu_env *env, struct obd_export *exp,
6344                          struct lu_fid *fid, struct md_op_data *op_data)
6345 {
6346         struct osd_device *osd = osd_dev(exp->exp_obd->obd_lu_dev);
6347
6348         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
6349 }
6350
6351 static const struct lu_object_operations osd_lu_obj_ops = {
6352         .loo_object_init      = osd_object_init,
6353         .loo_object_delete    = osd_object_delete,
6354         .loo_object_release   = osd_object_release,
6355         .loo_object_free      = osd_object_free,
6356         .loo_object_print     = osd_object_print,
6357         .loo_object_invariant = osd_object_invariant
6358 };
6359
6360 const struct lu_device_operations osd_lu_ops = {
6361         .ldo_object_alloc      = osd_object_alloc,
6362         .ldo_process_config    = osd_process_config,
6363         .ldo_recovery_complete = osd_recovery_complete,
6364         .ldo_prepare           = osd_prepare,
6365 };
6366
6367 static const struct lu_device_type_operations osd_device_type_ops = {
6368         .ldto_init = osd_type_init,
6369         .ldto_fini = osd_type_fini,
6370
6371         .ldto_start = osd_type_start,
6372         .ldto_stop  = osd_type_stop,
6373
6374         .ldto_device_alloc = osd_device_alloc,
6375         .ldto_device_free  = osd_device_free,
6376
6377         .ldto_device_init    = osd_device_init,
6378         .ldto_device_fini    = osd_device_fini
6379 };
6380
6381 static struct lu_device_type osd_device_type = {
6382         .ldt_tags     = LU_DEVICE_DT,
6383         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
6384         .ldt_ops      = &osd_device_type_ops,
6385         .ldt_ctx_tags = LCT_LOCAL,
6386 };
6387
6388 /*
6389  * lprocfs legacy support.
6390  */
6391 static struct obd_ops osd_obd_device_ops = {
6392         .o_owner = THIS_MODULE,
6393         .o_connect      = osd_obd_connect,
6394         .o_disconnect   = osd_obd_disconnect,
6395         .o_fid_alloc    = osd_fid_alloc,
6396 };
6397
6398 static int __init osd_mod_init(void)
6399 {
6400         int rc;
6401
6402         osd_oi_mod_init();
6403
6404         rc = lu_kmem_init(ldiskfs_caches);
6405         if (rc)
6406                 return rc;
6407
6408         rc = class_register_type(&osd_obd_device_ops, NULL, true,
6409                                  lprocfs_osd_module_vars,
6410                                  LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
6411         if (rc)
6412                 lu_kmem_fini(ldiskfs_caches);
6413         return rc;
6414 }
6415
6416 static void __exit osd_mod_exit(void)
6417 {
6418         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
6419         lu_kmem_fini(ldiskfs_caches);
6420 }
6421
6422 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
6423 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
6424 MODULE_LICENSE("GPL");
6425
6426 cfs_module(osd, "0.1.0", osd_mod_init, osd_mod_exit);