Whamcloud - gitweb
LU-1842 quota: add quota disk operations
[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, 2012, Whamcloud, Inc.
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_MDS
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 /* simple_mkdir() */
57 #include <lvfs.h>
58
59 /*
60  * struct OBD_{ALLOC,FREE}*()
61  * OBD_FAIL_CHECK
62  */
63 #include <obd_support.h>
64 /* struct ptlrpc_thread */
65 #include <lustre_net.h>
66
67 /* fid_is_local() */
68 #include <lustre_fid.h>
69
70 #include "osd_internal.h"
71 #include "osd_igif.h"
72
73 /* llo_* api support */
74 #include <md_object.h>
75 /* dt_acct_features */
76 #include <lquota.h>
77
78 #ifdef HAVE_LDISKFS_PDO
79 int ldiskfs_pdo = 1;
80 CFS_MODULE_PARM(ldiskfs_pdo, "i", int, 0644,
81                 "ldiskfs with parallel directory operations");
82 #else
83 int ldiskfs_pdo = 0;
84 #endif
85
86 static const char dot[] = ".";
87 static const char dotdot[] = "..";
88 static const char remote_obj_dir[] = "REM_OBJ_DIR";
89
90 static const struct lu_object_operations      osd_lu_obj_ops;
91 static const struct dt_object_operations      osd_obj_ops;
92 static const struct dt_object_operations      osd_obj_ea_ops;
93 static const struct dt_object_operations      osd_obj_otable_it_ops;
94 static const struct dt_index_operations       osd_index_iam_ops;
95 static const struct dt_index_operations       osd_index_ea_ops;
96
97 static int osd_has_index(const struct osd_object *obj)
98 {
99         return obj->oo_dt.do_index_ops != NULL;
100 }
101
102 static int osd_object_invariant(const struct lu_object *l)
103 {
104         return osd_invariant(osd_obj(l));
105 }
106
107 #ifdef HAVE_QUOTA_SUPPORT
108 static inline void
109 osd_push_ctxt(const struct lu_env *env, struct osd_ctxt *save, bool is_md)
110 {
111         struct md_ucred *uc;
112         struct cred     *tc;
113
114         if (!is_md)
115                 /* OFD support */
116                 return;
117
118         uc = md_ucred(env);
119
120         LASSERT(uc != NULL);
121
122         save->oc_uid = current_fsuid();
123         save->oc_gid = current_fsgid();
124         save->oc_cap = current_cap();
125         if ((tc = prepare_creds())) {
126                 tc->fsuid         = uc->mu_fsuid;
127                 tc->fsgid         = uc->mu_fsgid;
128                 commit_creds(tc);
129         }
130         /* XXX not suboptimal */
131         cfs_curproc_cap_unpack(uc->mu_cap);
132 }
133
134 static inline void
135 osd_pop_ctxt(struct osd_ctxt *save, bool is_md)
136 {
137         struct cred *tc;
138
139         if (!is_md)
140                 /* OFD support */
141                 return;
142
143         if ((tc = prepare_creds())) {
144                 tc->fsuid         = save->oc_uid;
145                 tc->fsgid         = save->oc_gid;
146                 tc->cap_effective = save->oc_cap;
147                 commit_creds(tc);
148         }
149 }
150 #endif
151
152 /*
153  * Concurrency: doesn't matter
154  */
155 static int osd_read_locked(const struct lu_env *env, struct osd_object *o)
156 {
157         return osd_oti_get(env)->oti_r_locks > 0;
158 }
159
160 /*
161  * Concurrency: doesn't matter
162  */
163 static int osd_write_locked(const struct lu_env *env, struct osd_object *o)
164 {
165         struct osd_thread_info *oti = osd_oti_get(env);
166         return oti->oti_w_locks > 0 && o->oo_owner == env;
167 }
168
169 /*
170  * Concurrency: doesn't access mutable data
171  */
172 static int osd_root_get(const struct lu_env *env,
173                         struct dt_device *dev, struct lu_fid *f)
174 {
175         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
176         return 0;
177 }
178
179 /*
180  * OSD object methods.
181  */
182
183 /*
184  * Concurrency: no concurrent access is possible that early in object
185  * life-cycle.
186  */
187 static struct lu_object *osd_object_alloc(const struct lu_env *env,
188                                           const struct lu_object_header *hdr,
189                                           struct lu_device *d)
190 {
191         struct osd_object *mo;
192
193         OBD_ALLOC_PTR(mo);
194         if (mo != NULL) {
195                 struct lu_object *l;
196
197                 l = &mo->oo_dt.do_lu;
198                 dt_object_init(&mo->oo_dt, NULL, d);
199                 if (osd_dev(d)->od_iop_mode)
200                         mo->oo_dt.do_ops = &osd_obj_ea_ops;
201                 else
202                         mo->oo_dt.do_ops = &osd_obj_ops;
203
204                 l->lo_ops = &osd_lu_obj_ops;
205                 cfs_init_rwsem(&mo->oo_sem);
206                 cfs_init_rwsem(&mo->oo_ext_idx_sem);
207                 cfs_spin_lock_init(&mo->oo_guard);
208                 return l;
209         } else {
210                 return NULL;
211         }
212 }
213
214 static int osd_get_lma(struct inode *inode, struct dentry *dentry,
215                        struct lustre_mdt_attrs *lma)
216 {
217         int rc;
218
219         dentry->d_inode = inode;
220         rc = inode->i_op->getxattr(dentry, XATTR_NAME_LMA, (void *)lma,
221                                    sizeof(*lma));
222         if (rc > 0) {
223                 /* Check LMA compatibility */
224                 if (lma->lma_incompat & ~cpu_to_le32(LMA_INCOMPAT_SUPP)) {
225                         CWARN("%.16s: unsupported incompat LMA feature(s) "
226                               "%lx/%#x\n",
227                               LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
228                               inode->i_ino, le32_to_cpu(lma->lma_incompat) &
229                                                         ~LMA_INCOMPAT_SUPP);
230                         rc = -ENOSYS;
231                 } else {
232                         lustre_lma_swab(lma);
233                         rc = 0;
234                 }
235         } else if (rc == 0) {
236                 rc = -ENODATA;
237         }
238
239         return rc;
240 }
241
242 /*
243  * retrieve object from backend ext fs.
244  **/
245 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
246                        struct osd_inode_id *id)
247 {
248         struct inode *inode = NULL;
249
250         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
251         if (IS_ERR(inode)) {
252                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
253                        id->oii_ino, PTR_ERR(inode));
254         } else if (id->oii_gen != OSD_OII_NOGEN &&
255                    inode->i_generation != id->oii_gen) {
256                 CDEBUG(D_INODE, "unmatched inode: ino = %u, gen0 = %u, "
257                        "gen1 = %u\n",
258                        id->oii_ino, id->oii_gen, inode->i_generation);
259                 iput(inode);
260                 inode = ERR_PTR(-ESTALE);
261         } else if (inode->i_nlink == 0) {
262                 /* due to parallel readdir and unlink,
263                 * we can have dead inode here. */
264                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
265                 make_bad_inode(inode);
266                 iput(inode);
267                 inode = ERR_PTR(-ESTALE);
268         } else if (is_bad_inode(inode)) {
269                 CWARN("%.16s: bad inode: ino = %u\n",
270                 LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, id->oii_ino);
271                 iput(inode);
272                 inode = ERR_PTR(-ENOENT);
273         } else {
274                 if (id->oii_gen == OSD_OII_NOGEN)
275                         osd_id_gen(id, inode->i_ino, inode->i_generation);
276
277                 /* Do not update file c/mtime in ldiskfs.
278                  * NB: we don't have any lock to protect this because we don't
279                  * have reference on osd_object now, but contention with
280                  * another lookup + attr_set can't happen in the tiny window
281                  * between if (...) and set S_NOCMTIME. */
282                 if (!(inode->i_flags & S_NOCMTIME))
283                         inode->i_flags |= S_NOCMTIME;
284         }
285         return inode;
286 }
287
288 struct inode *osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
289                            struct osd_inode_id *id, struct lu_fid *fid)
290 {
291         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
292         struct inode            *inode;
293         int                      rc;
294
295         inode = osd_iget(info, dev, id);
296         if (IS_ERR(inode))
297                 return inode;
298
299         rc = osd_get_lma(inode, &info->oti_obj_dentry, lma);
300         if (rc == 0) {
301                 *fid = lma->lma_self_fid;
302         } else if (rc == -ENODATA) {
303                 LU_IGIF_BUILD(fid, inode->i_ino, inode->i_generation);
304         } else {
305                 iput(inode);
306                 inode = ERR_PTR(rc);
307         }
308         return inode;
309 }
310
311 static struct inode *
312 osd_iget_verify(struct osd_thread_info *info, struct osd_device *dev,
313                 struct osd_inode_id *id, const struct lu_fid *fid)
314 {
315         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
316         struct inode            *inode;
317         int                      rc;
318
319         inode = osd_iget(info, dev, id);
320         if (IS_ERR(inode))
321                 return inode;
322
323         rc = osd_get_lma(inode, &info->oti_obj_dentry, lma);
324         if (rc != 0) {
325                 if (rc == -ENODATA) {
326                         CDEBUG(D_LFSCK, "inconsistent obj: NULL, %lu, "DFID"\n",
327                                inode->i_ino, PFID(fid));
328                         rc = -EREMCHG;
329                 }
330                 iput(inode);
331                 return ERR_PTR(rc);
332         }
333
334         if (!lu_fid_eq(fid, &lma->lma_self_fid)) {
335                 CDEBUG(D_LFSCK, "inconsistent obj: "DFID", %lu, "DFID"\n",
336                        PFID(&lma->lma_self_fid), inode->i_ino, PFID(fid));
337                 iput(inode);
338                 return ERR_PTR(EREMCHG);
339         }
340         return inode;
341 }
342
343 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
344                           const struct lu_fid *fid,
345                           const struct lu_object_conf *conf)
346 {
347         struct osd_thread_info *info;
348         struct lu_device       *ldev   = obj->oo_dt.do_lu.lo_dev;
349         struct osd_device      *dev;
350         struct osd_idmap_cache *oic;
351         struct osd_inode_id    *id;
352         struct inode           *inode;
353         struct osd_scrub       *scrub;
354         struct scrub_file      *sf;
355         int                     result;
356         int                     verify = 0;
357         ENTRY;
358
359         LINVRNT(osd_invariant(obj));
360         LASSERT(obj->oo_inode == NULL);
361         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID, PFID(fid));
362
363         dev = osd_dev(ldev);
364         scrub = &dev->od_scrub;
365         sf = &scrub->os_file;
366         info = osd_oti_get(env);
367         LASSERT(info);
368         oic = &info->oti_cache;
369         id  = &oic->oic_lid;
370
371         if (OBD_FAIL_CHECK(OBD_FAIL_OST_ENOENT))
372                 RETURN(-ENOENT);
373
374         if (fid_is_norm(fid)) {
375                 /* Search order: 1. per-thread cache. */
376                 if (lu_fid_eq(fid, &oic->oic_fid)) {
377                         goto iget;
378                 } else if (!cfs_list_empty(&scrub->os_inconsistent_items)) {
379                         /* Search order: 2. OI scrub pending list. */
380                         result = osd_oii_lookup(dev, fid, id);
381                         if (result == 0)
382                                 goto iget;
383                 }
384
385                 if (sf->sf_flags & SF_INCONSISTENT)
386                         verify = 1;
387         }
388
389         /*
390          * Objects are created as locking anchors or place holders for objects
391          * yet to be created. No need to osd_oi_lookup() at here because FID
392          * shouldn't never be re-used, if it's really a duplicate FID from
393          * unexpected reason, we should be able to detect it later by calling
394          * do_create->osd_oi_insert()
395          */
396         if (conf != NULL && (conf->loc_flags & LOC_F_NEW) != 0)
397                 GOTO(out, result = 0);
398
399         /* Search order: 3. OI files. */
400         result = osd_oi_lookup(info, dev, fid, id);
401         if (result == -ENOENT) {
402                 if (!fid_is_norm(fid) ||
403                     !ldiskfs_test_bit(osd_oi_fid2idx(dev,fid),
404                                       sf->sf_oi_bitmap))
405                         GOTO(out, result = 0);
406
407                 goto trigger;
408         }
409
410         if (result != 0)
411                 GOTO(out, result);
412
413 iget:
414         if (verify == 0)
415                 inode = osd_iget(info, dev, id);
416         else
417                 inode = osd_iget_verify(info, dev, id, fid);
418         if (IS_ERR(inode)) {
419                 result = PTR_ERR(inode);
420                 if (result == -ENOENT || result == -ESTALE) {
421                         fid_zero(&oic->oic_fid);
422                         result = 0;
423                 } else if (result == -EREMCHG) {
424
425 trigger:
426                         if (thread_is_running(&scrub->os_thread)) {
427                                 result = -EINPROGRESS;
428                         } else if (!scrub->os_no_scrub) {
429                                 result = osd_scrub_start(dev);
430                                 LCONSOLE_ERROR("%.16s: trigger OI scrub by RPC "
431                                                "for "DFID", rc = %d [1]\n",
432                                                LDISKFS_SB(osd_sb(dev))->s_es->\
433                                                s_volume_name,PFID(fid), result);
434                                 if (result == 0 || result == -EALREADY)
435                                         result = -EINPROGRESS;
436                                 else
437                                         result = -EREMCHG;
438                         }
439                 }
440
441                 GOTO(out, result);
442         }
443
444         obj->oo_inode = inode;
445         LASSERT(obj->oo_inode->i_sb == osd_sb(dev));
446         if (dev->od_iop_mode) {
447                 obj->oo_compat_dot_created = 1;
448                 obj->oo_compat_dotdot_created = 1;
449         }
450
451         if (!S_ISDIR(inode->i_mode) || !ldiskfs_pdo) /* done */
452                 GOTO(out, result = 0);
453
454         LASSERT(obj->oo_hl_head == NULL);
455         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
456         if (obj->oo_hl_head == NULL) {
457                 obj->oo_inode = NULL;
458                 iput(inode);
459                 GOTO(out, result = -ENOMEM);
460         }
461         GOTO(out, result = 0);
462
463 out:
464         LINVRNT(osd_invariant(obj));
465         return result;
466 }
467
468 /*
469  * Concurrency: shouldn't matter.
470  */
471 static void osd_object_init0(struct osd_object *obj)
472 {
473         LASSERT(obj->oo_inode != NULL);
474         obj->oo_dt.do_body_ops = &osd_body_ops;
475         obj->oo_dt.do_lu.lo_header->loh_attr |=
476                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
477 }
478
479 /*
480  * Concurrency: no concurrent access is possible that early in object
481  * life-cycle.
482  */
483 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
484                            const struct lu_object_conf *conf)
485 {
486         struct osd_object *obj = osd_obj(l);
487         int result;
488
489         LINVRNT(osd_invariant(obj));
490
491         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
492         obj->oo_dt.do_body_ops = &osd_body_ops_new;
493         if (result == 0) {
494                 if (obj->oo_inode != NULL) {
495                         osd_object_init0(obj);
496                 } else if (fid_is_otable_it(&l->lo_header->loh_fid)) {
497                         obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
498                         /* LFSCK iterator object is special without inode */
499                         l->lo_header->loh_attr |= LOHA_EXISTS;
500                 }
501         }
502         LINVRNT(osd_invariant(obj));
503         return result;
504 }
505
506 /*
507  * Concurrency: no concurrent access is possible that late in object
508  * life-cycle.
509  */
510 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
511 {
512         struct osd_object *obj = osd_obj(l);
513
514         LINVRNT(osd_invariant(obj));
515
516         dt_object_fini(&obj->oo_dt);
517         if (obj->oo_hl_head != NULL)
518                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
519         OBD_FREE_PTR(obj);
520 }
521
522 /*
523  * Concurrency: no concurrent access is possible that late in object
524  * life-cycle.
525  */
526 static void osd_index_fini(struct osd_object *o)
527 {
528         struct iam_container *bag;
529
530         if (o->oo_dir != NULL) {
531                 bag = &o->oo_dir->od_container;
532                 if (o->oo_inode != NULL) {
533                         if (bag->ic_object == o->oo_inode)
534                                 iam_container_fini(bag);
535                 }
536                 OBD_FREE_PTR(o->oo_dir);
537                 o->oo_dir = NULL;
538         }
539 }
540
541 /*
542  * Concurrency: no concurrent access is possible that late in object
543  * life-cycle (for all existing callers, that is. New callers have to provide
544  * their own locking.)
545  */
546 static int osd_inode_unlinked(const struct inode *inode)
547 {
548         return inode->i_nlink == 0;
549 }
550
551 enum {
552         OSD_TXN_OI_DELETE_CREDITS    = 20,
553         OSD_TXN_INODE_DELETE_CREDITS = 20
554 };
555
556 /*
557  * Journal
558  */
559
560 #if OSD_THANDLE_STATS
561 /**
562  * Set time when the handle is allocated
563  */
564 static void osd_th_alloced(struct osd_thandle *oth)
565 {
566         oth->oth_alloced = cfs_time_current();
567 }
568
569 /**
570  * Set time when the handle started
571  */
572 static void osd_th_started(struct osd_thandle *oth)
573 {
574         oth->oth_started = cfs_time_current();
575 }
576
577 /**
578  * Helper function to convert time interval to microseconds packed in
579  * long int (default time units for the counter in "stats" initialized
580  * by lu_time_init() )
581  */
582 static long interval_to_usec(cfs_time_t start, cfs_time_t end)
583 {
584         struct timeval val;
585
586         cfs_duration_usec(cfs_time_sub(end, start), &val);
587         return val.tv_sec * 1000000 + val.tv_usec;
588 }
589
590 /**
591  * Check whether the we deal with this handle for too long.
592  */
593 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
594                                 cfs_time_t alloced, cfs_time_t started,
595                                 cfs_time_t closed)
596 {
597         cfs_time_t now = cfs_time_current();
598
599         LASSERT(dev != NULL);
600
601         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
602                             interval_to_usec(alloced, started));
603         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
604                             interval_to_usec(started, closed));
605         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
606                             interval_to_usec(closed, now));
607
608         if (cfs_time_before(cfs_time_add(alloced, cfs_time_seconds(30)), now)) {
609                 CWARN("transaction handle %p was open for too long: "
610                       "now "CFS_TIME_T" ,"
611                       "alloced "CFS_TIME_T" ,"
612                       "started "CFS_TIME_T" ,"
613                       "closed "CFS_TIME_T"\n",
614                       oth, now, alloced, started, closed);
615                 libcfs_debug_dumpstack(NULL);
616         }
617 }
618
619 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
620 {                                                                       \
621         cfs_time_t __closed = cfs_time_current();                       \
622         cfs_time_t __alloced = oth->oth_alloced;                        \
623         cfs_time_t __started = oth->oth_started;                        \
624                                                                         \
625         expr;                                                           \
626         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
627 }
628
629 #else /* OSD_THANDLE_STATS */
630
631 #define osd_th_alloced(h)                  do {} while(0)
632 #define osd_th_started(h)                  do {} while(0)
633 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
634
635 #endif /* OSD_THANDLE_STATS */
636
637 /*
638  * Concurrency: doesn't access mutable data.
639  */
640 static int osd_param_is_sane(const struct osd_device *dev,
641                              const struct thandle *th)
642 {
643         struct osd_thandle *oh;
644         oh = container_of0(th, struct osd_thandle, ot_super);
645         return oh->ot_credits <= osd_journal(dev)->j_max_transaction_buffers;
646 }
647
648 /*
649  * Concurrency: shouldn't matter.
650  */
651 #ifdef HAVE_LDISKFS_JOURNAL_CALLBACK_ADD
652 static void osd_trans_commit_cb(struct super_block *sb,
653                                 struct journal_callback *jcb, int error)
654 #else
655 static void osd_trans_commit_cb(struct journal_callback *jcb, int error)
656 #endif
657 {
658         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
659         struct thandle     *th  = &oh->ot_super;
660         struct lu_device   *lud = &th->th_dev->dd_lu_dev;
661         struct dt_txn_commit_cb *dcb, *tmp;
662
663         LASSERT(oh->ot_handle == NULL);
664
665         if (error)
666                 CERROR("transaction @0x%p commit error: %d\n", th, error);
667
668         dt_txn_hook_commit(th);
669
670         /* call per-transaction callbacks if any */
671         cfs_list_for_each_entry_safe(dcb, tmp, &oh->ot_dcb_list, dcb_linkage) {
672                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
673                          "commit callback entry: magic=%x name='%s'\n",
674                          dcb->dcb_magic, dcb->dcb_name);
675                 cfs_list_del_init(&dcb->dcb_linkage);
676                 dcb->dcb_func(NULL, th, dcb, error);
677         }
678
679         lu_ref_del_at(&lud->ld_reference, oh->ot_dev_link, "osd-tx", th);
680         lu_device_put(lud);
681         th->th_dev = NULL;
682
683         lu_context_exit(&th->th_ctx);
684         lu_context_fini(&th->th_ctx);
685         OBD_FREE_PTR(oh);
686 }
687
688 static struct thandle *osd_trans_create(const struct lu_env *env,
689                                         struct dt_device *d)
690 {
691         struct osd_thread_info *oti = osd_oti_get(env);
692         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
693         struct osd_thandle     *oh;
694         struct thandle         *th;
695         ENTRY;
696
697         /* on pending IO in this thread should left from prev. request */
698         LASSERT(cfs_atomic_read(&iobuf->dr_numreqs) == 0);
699
700         th = ERR_PTR(-ENOMEM);
701         OBD_ALLOC_GFP(oh, sizeof *oh, CFS_ALLOC_IO);
702         if (oh != NULL) {
703                 oh->ot_quota_trans = &oti->oti_quota_trans;
704                 memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
705                 th = &oh->ot_super;
706                 th->th_dev = d;
707                 th->th_result = 0;
708                 th->th_tags = LCT_TX_HANDLE;
709                 oh->ot_credits = 0;
710                 oti->oti_dev = osd_dt_dev(d);
711                 CFS_INIT_LIST_HEAD(&oh->ot_dcb_list);
712                 osd_th_alloced(oh);
713         }
714         RETURN(th);
715 }
716
717 /*
718  * Concurrency: shouldn't matter.
719  */
720 int osd_trans_start(const struct lu_env *env, struct dt_device *d,
721                     struct thandle *th)
722 {
723         struct osd_thread_info *oti = osd_oti_get(env);
724         struct osd_device  *dev = osd_dt_dev(d);
725         handle_t           *jh;
726         struct osd_thandle *oh;
727         int rc;
728
729         ENTRY;
730
731         LASSERT(current->journal_info == NULL);
732
733         oh = container_of0(th, struct osd_thandle, ot_super);
734         LASSERT(oh != NULL);
735         LASSERT(oh->ot_handle == NULL);
736
737         rc = dt_txn_hook_start(env, d, th);
738         if (rc != 0)
739                 GOTO(out, rc);
740
741         if (!osd_param_is_sane(dev, th)) {
742                 CWARN("%.16s: too many transaction credits (%d > %d)\n",
743                       LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
744                       oh->ot_credits,
745                       osd_journal(dev)->j_max_transaction_buffers);
746                 /* XXX Limit the credits to 'max_transaction_buffers', and
747                  *     let the underlying filesystem to catch the error if
748                  *     we really need so many credits.
749                  *
750                  *     This should be removed when we can calculate the
751                  *     credits precisely. */
752                 oh->ot_credits = osd_journal(dev)->j_max_transaction_buffers;
753 #ifdef OSD_TRACK_DECLARES
754                 CERROR("  attr_set: %d, punch: %d, xattr_set: %d,\n",
755                        oh->ot_declare_attr_set, oh->ot_declare_punch,
756                        oh->ot_declare_xattr_set);
757                 CERROR("  create: %d, ref_add: %d, ref_del: %d, write: %d\n",
758                        oh->ot_declare_create, oh->ot_declare_ref_add,
759                        oh->ot_declare_ref_del, oh->ot_declare_write);
760                 CERROR("  insert: %d, delete: %d, destroy: %d\n",
761                        oh->ot_declare_insert, oh->ot_declare_delete,
762                        oh->ot_declare_destroy);
763 #endif
764         }
765
766         /*
767          * XXX temporary stuff. Some abstraction layer should
768          * be used.
769          */
770         jh = ldiskfs_journal_start_sb(osd_sb(dev), oh->ot_credits);
771         osd_th_started(oh);
772         if (!IS_ERR(jh)) {
773                 oh->ot_handle = jh;
774                 LASSERT(oti->oti_txns == 0);
775                 lu_context_init(&th->th_ctx, th->th_tags);
776                 lu_context_enter(&th->th_ctx);
777
778                 lu_device_get(&d->dd_lu_dev);
779                 oh->ot_dev_link = lu_ref_add(&d->dd_lu_dev.ld_reference,
780                                              "osd-tx", th);
781                 oti->oti_txns++;
782                 rc = 0;
783         } else {
784                 rc = PTR_ERR(jh);
785         }
786 out:
787         RETURN(rc);
788 }
789
790 /*
791  * Concurrency: shouldn't matter.
792  */
793 static int osd_trans_stop(const struct lu_env *env, struct thandle *th)
794 {
795         int                     rc = 0;
796         struct osd_thandle     *oh;
797         struct osd_thread_info *oti = osd_oti_get(env);
798         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
799         struct qsd_instance    *qsd = oti->oti_dev->od_quota_slave;
800         ENTRY;
801
802         oh = container_of0(th, struct osd_thandle, ot_super);
803
804         if (qsd != NULL)
805                 /* inform the quota slave device that the transaction is
806                  * stopping */
807                 qsd_op_end(env, qsd, oh->ot_quota_trans);
808         oh->ot_quota_trans = NULL;
809
810         if (oh->ot_handle != NULL) {
811                 handle_t *hdl = oh->ot_handle;
812
813                 /*
814                  * add commit callback
815                  * notice we don't do this in osd_trans_start()
816                  * as underlying transaction can change during truncate
817                  */
818                 osd_journal_callback_set(hdl, osd_trans_commit_cb,
819                                          &oh->ot_jcb);
820
821                 LASSERT(oti->oti_txns == 1);
822                 oti->oti_txns--;
823                 rc = dt_txn_hook_stop(env, th);
824                 if (rc != 0)
825                         CERROR("Failure in transaction hook: %d\n", rc);
826
827                 /* hook functions might modify th_sync */
828                 hdl->h_sync = th->th_sync;
829
830                 oh->ot_handle = NULL;
831                 OSD_CHECK_SLOW_TH(oh, oti->oti_dev,
832                                   rc = ldiskfs_journal_stop(hdl));
833                 if (rc != 0)
834                         CERROR("Failure to stop transaction: %d\n", rc);
835         } else {
836                 OBD_FREE_PTR(oh);
837         }
838
839         /* as we want IO to journal and data IO be concurrent, we don't block
840          * awaiting data IO completion in osd_do_bio(), instead we wait here
841          * once transaction is submitted to the journal. all reqular requests
842          * don't do direct IO (except read/write), thus this wait_event becomes
843          * no-op for them.
844          *
845          * IMPORTANT: we have to wait till any IO submited by the thread is
846          * completed otherwise iobuf may be corrupted by different request
847          */
848         cfs_wait_event(iobuf->dr_wait,
849                        cfs_atomic_read(&iobuf->dr_numreqs) == 0);
850         if (!rc)
851                 rc = iobuf->dr_error;
852
853         RETURN(rc);
854 }
855
856 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
857 {
858         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
859                                                ot_super);
860
861         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
862         LASSERT(&dcb->dcb_func != NULL);
863         cfs_list_add(&dcb->dcb_linkage, &oh->ot_dcb_list);
864
865         return 0;
866 }
867
868 /*
869  * Called just before object is freed. Releases all resources except for
870  * object itself (that is released by osd_object_free()).
871  *
872  * Concurrency: no concurrent access is possible that late in object
873  * life-cycle.
874  */
875 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
876 {
877         struct osd_object *obj   = osd_obj(l);
878         struct inode      *inode = obj->oo_inode;
879
880         LINVRNT(osd_invariant(obj));
881
882         /*
883          * If object is unlinked remove fid->ino mapping from object index.
884          */
885
886         osd_index_fini(obj);
887         if (inode != NULL) {
888                 iput(inode);
889                 obj->oo_inode = NULL;
890         }
891 }
892
893 /*
894  * Concurrency: ->loo_object_release() is called under site spin-lock.
895  */
896 static void osd_object_release(const struct lu_env *env,
897                                struct lu_object *l)
898 {
899 }
900
901 /*
902  * Concurrency: shouldn't matter.
903  */
904 static int osd_object_print(const struct lu_env *env, void *cookie,
905                             lu_printer_t p, const struct lu_object *l)
906 {
907         struct osd_object *o = osd_obj(l);
908         struct iam_descr  *d;
909
910         if (o->oo_dir != NULL)
911                 d = o->oo_dir->od_container.ic_descr;
912         else
913                 d = NULL;
914         return (*p)(env, cookie,
915                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
916                     o, o->oo_inode,
917                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
918                     o->oo_inode ? o->oo_inode->i_generation : 0,
919                     d ? d->id_ops->id_name : "plain");
920 }
921
922 /*
923  * Concurrency: shouldn't matter.
924  */
925 int osd_statfs(const struct lu_env *env, struct dt_device *d,
926                struct obd_statfs *sfs)
927 {
928         struct osd_device  *osd = osd_dt_dev(d);
929         struct super_block *sb = osd_sb(osd);
930         struct kstatfs     *ksfs;
931         int result = 0;
932
933         if (unlikely(osd->od_mnt == NULL))
934                 return -EINPROGRESS;
935
936         /* osd_lproc.c call this without env, allocate ksfs for that case */
937         if (unlikely(env == NULL)) {
938                 OBD_ALLOC_PTR(ksfs);
939                 if (ksfs == NULL)
940                         return -ENOMEM;
941         } else {
942                 ksfs = &osd_oti_get(env)->oti_ksfs;
943         }
944
945         cfs_spin_lock(&osd->od_osfs_lock);
946         /* cache 1 second */
947         if (cfs_time_before_64(osd->od_osfs_age, cfs_time_shift_64(-1))) {
948                 result = sb->s_op->statfs(sb->s_root, ksfs);
949                 if (likely(result == 0)) { /* N.B. statfs can't really fail */
950                         osd->od_osfs_age = cfs_time_current_64();
951                         statfs_pack(&osd->od_statfs, ksfs);
952                 }
953         }
954
955         if (likely(result == 0))
956                 *sfs = osd->od_statfs;
957         cfs_spin_unlock(&osd->od_osfs_lock);
958
959         if (unlikely(env == NULL))
960                 OBD_FREE_PTR(ksfs);
961
962         return result;
963 }
964
965 /*
966  * Concurrency: doesn't access mutable data.
967  */
968 static void osd_conf_get(const struct lu_env *env,
969                          const struct dt_device *dev,
970                          struct dt_device_param *param)
971 {
972         struct super_block *sb = osd_sb(osd_dt_dev(dev));
973
974         /*
975          * XXX should be taken from not-yet-existing fs abstraction layer.
976          */
977         param->ddp_mnt = osd_dt_dev(dev)->od_mnt;
978         param->ddp_max_name_len = LDISKFS_NAME_LEN;
979         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
980         param->ddp_block_shift  = sb->s_blocksize_bits;
981         param->ddp_mount_type     = LDD_MT_LDISKFS;
982         param->ddp_mntopts      = 0;
983         if (test_opt(sb, XATTR_USER))
984                 param->ddp_mntopts |= MNTOPT_USERXATTR;
985         if (test_opt(sb, POSIX_ACL))
986                 param->ddp_mntopts |= MNTOPT_ACL;
987
988 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
989         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EA_INODE))
990                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE;
991         else
992 #endif
993                 param->ddp_max_ea_size = sb->s_blocksize;
994
995 }
996
997 /**
998  * Helper function to get and fill the buffer with input values.
999  */
1000 static struct lu_buf *osd_buf_get(const struct lu_env *env, void *area, ssize_t len)
1001 {
1002         struct lu_buf *buf;
1003
1004         buf = &osd_oti_get(env)->oti_buf;
1005         buf->lb_buf = area;
1006         buf->lb_len = len;
1007         return buf;
1008 }
1009
1010 /*
1011  * Concurrency: shouldn't matter.
1012  */
1013 static int osd_sync(const struct lu_env *env, struct dt_device *d)
1014 {
1015         CDEBUG(D_HA, "syncing OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1016         return ldiskfs_force_commit(osd_sb(osd_dt_dev(d)));
1017 }
1018
1019 /**
1020  * Start commit for OSD device.
1021  *
1022  * An implementation of dt_commit_async method for OSD device.
1023  * Asychronously starts underlayng fs sync and thereby a transaction
1024  * commit.
1025  *
1026  * \param env environment
1027  * \param d dt device
1028  *
1029  * \see dt_device_operations
1030  */
1031 static int osd_commit_async(const struct lu_env *env,
1032                             struct dt_device *d)
1033 {
1034         struct super_block *s = osd_sb(osd_dt_dev(d));
1035         ENTRY;
1036
1037         CDEBUG(D_HA, "async commit OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1038         RETURN(s->s_op->sync_fs(s, 0));
1039 }
1040
1041 /*
1042  * Concurrency: shouldn't matter.
1043  */
1044
1045 static int osd_ro(const struct lu_env *env, struct dt_device *d)
1046 {
1047         struct super_block *sb = osd_sb(osd_dt_dev(d));
1048         int rc;
1049         ENTRY;
1050
1051         CERROR("*** setting %s read-only ***\n", osd_dt_dev(d)->od_svname);
1052
1053         rc = __lvfs_set_rdonly(sb->s_bdev, LDISKFS_SB(sb)->journal_bdev);
1054         RETURN(rc);
1055 }
1056
1057 /*
1058  * Concurrency: serialization provided by callers.
1059  */
1060 static int osd_init_capa_ctxt(const struct lu_env *env, struct dt_device *d,
1061                               int mode, unsigned long timeout, __u32 alg,
1062                               struct lustre_capa_key *keys)
1063 {
1064         struct osd_device *dev = osd_dt_dev(d);
1065         ENTRY;
1066
1067         dev->od_fl_capa = mode;
1068         dev->od_capa_timeout = timeout;
1069         dev->od_capa_alg = alg;
1070         dev->od_capa_keys = keys;
1071         RETURN(0);
1072 }
1073
1074 /**
1075  * Concurrency: serialization provided by callers.
1076  */
1077 static void osd_init_quota_ctxt(const struct lu_env *env, struct dt_device *d,
1078                                struct dt_quota_ctxt *ctxt, void *data)
1079 {
1080         struct obd_device *obd = (void *)ctxt;
1081         struct vfsmount *mnt = (struct vfsmount *)data;
1082         ENTRY;
1083
1084         obd->u.obt.obt_sb = mnt->mnt_root->d_inode->i_sb;
1085         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
1086         obd->obd_lvfs_ctxt.pwdmnt = mnt;
1087         obd->obd_lvfs_ctxt.pwd = mnt->mnt_root;
1088         obd->obd_lvfs_ctxt.fs = get_ds();
1089
1090         EXIT;
1091 }
1092
1093 /**
1094  * Note: we do not count into QUOTA here.
1095  * If we mount with --data_journal we may need more.
1096  */
1097 const int osd_dto_credits_noquota[DTO_NR] = {
1098         /**
1099          * Insert/Delete.
1100          * INDEX_EXTRA_TRANS_BLOCKS(8) +
1101          * SINGLEDATA_TRANS_BLOCKS(8)
1102          * XXX Note: maybe iam need more, since iam have more level than
1103          *           EXT3 htree.
1104          */
1105         [DTO_INDEX_INSERT]  = 16,
1106         [DTO_INDEX_DELETE]  = 16,
1107         /**
1108          * Used for OI scrub
1109          */
1110         [DTO_INDEX_UPDATE]  = 16,
1111         /**
1112          * Create a object. The same as create object in EXT3.
1113          * DATA_TRANS_BLOCKS(14) +
1114          * INDEX_EXTRA_BLOCKS(8) +
1115          * 3(inode bits, groups, GDT)
1116          */
1117         [DTO_OBJECT_CREATE] = 25,
1118         /**
1119          * XXX: real credits to be fixed
1120          */
1121         [DTO_OBJECT_DELETE] = 25,
1122         /**
1123          * Attr set credits (inode)
1124          */
1125         [DTO_ATTR_SET_BASE] = 1,
1126         /**
1127          * Xattr set. The same as xattr of EXT3.
1128          * DATA_TRANS_BLOCKS(14)
1129          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
1130          * are also counted in. Do not know why?
1131          */
1132         [DTO_XATTR_SET]     = 14,
1133         [DTO_LOG_REC]       = 14,
1134         /**
1135          * credits for inode change during write.
1136          */
1137         [DTO_WRITE_BASE]    = 3,
1138         /**
1139          * credits for single block write.
1140          */
1141         [DTO_WRITE_BLOCK]   = 14,
1142         /**
1143          * Attr set credits for chown.
1144          * This is extra credits for setattr, and it is null without quota
1145          */
1146         [DTO_ATTR_SET_CHOWN]= 0
1147 };
1148
1149 static const struct dt_device_operations osd_dt_ops = {
1150         .dt_root_get       = osd_root_get,
1151         .dt_statfs         = osd_statfs,
1152         .dt_trans_create   = osd_trans_create,
1153         .dt_trans_start    = osd_trans_start,
1154         .dt_trans_stop     = osd_trans_stop,
1155         .dt_trans_cb_add   = osd_trans_cb_add,
1156         .dt_conf_get       = osd_conf_get,
1157         .dt_sync           = osd_sync,
1158         .dt_ro             = osd_ro,
1159         .dt_commit_async   = osd_commit_async,
1160         .dt_init_capa_ctxt = osd_init_capa_ctxt,
1161         .dt_init_quota_ctxt= osd_init_quota_ctxt,
1162 };
1163
1164 static void osd_object_read_lock(const struct lu_env *env,
1165                                  struct dt_object *dt, unsigned role)
1166 {
1167         struct osd_object *obj = osd_dt_obj(dt);
1168         struct osd_thread_info *oti = osd_oti_get(env);
1169
1170         LINVRNT(osd_invariant(obj));
1171
1172         LASSERT(obj->oo_owner != env);
1173         cfs_down_read_nested(&obj->oo_sem, role);
1174
1175         LASSERT(obj->oo_owner == NULL);
1176         oti->oti_r_locks++;
1177 }
1178
1179 static void osd_object_write_lock(const struct lu_env *env,
1180                                   struct dt_object *dt, unsigned role)
1181 {
1182         struct osd_object *obj = osd_dt_obj(dt);
1183         struct osd_thread_info *oti = osd_oti_get(env);
1184
1185         LINVRNT(osd_invariant(obj));
1186
1187         LASSERT(obj->oo_owner != env);
1188         cfs_down_write_nested(&obj->oo_sem, role);
1189
1190         LASSERT(obj->oo_owner == NULL);
1191         obj->oo_owner = env;
1192         oti->oti_w_locks++;
1193 }
1194
1195 static void osd_object_read_unlock(const struct lu_env *env,
1196                                    struct dt_object *dt)
1197 {
1198         struct osd_object *obj = osd_dt_obj(dt);
1199         struct osd_thread_info *oti = osd_oti_get(env);
1200
1201         LINVRNT(osd_invariant(obj));
1202
1203         LASSERT(oti->oti_r_locks > 0);
1204         oti->oti_r_locks--;
1205         cfs_up_read(&obj->oo_sem);
1206 }
1207
1208 static void osd_object_write_unlock(const struct lu_env *env,
1209                                     struct dt_object *dt)
1210 {
1211         struct osd_object *obj = osd_dt_obj(dt);
1212         struct osd_thread_info *oti = osd_oti_get(env);
1213
1214         LINVRNT(osd_invariant(obj));
1215
1216         LASSERT(obj->oo_owner == env);
1217         LASSERT(oti->oti_w_locks > 0);
1218         oti->oti_w_locks--;
1219         obj->oo_owner = NULL;
1220         cfs_up_write(&obj->oo_sem);
1221 }
1222
1223 static int osd_object_write_locked(const struct lu_env *env,
1224                                    struct dt_object *dt)
1225 {
1226         struct osd_object *obj = osd_dt_obj(dt);
1227
1228         LINVRNT(osd_invariant(obj));
1229
1230         return obj->oo_owner == env;
1231 }
1232
1233 static int capa_is_sane(const struct lu_env *env,
1234                         struct osd_device *dev,
1235                         struct lustre_capa *capa,
1236                         struct lustre_capa_key *keys)
1237 {
1238         struct osd_thread_info *oti = osd_oti_get(env);
1239         struct lustre_capa *tcapa = &oti->oti_capa;
1240         struct obd_capa *oc;
1241         int i, rc = 0;
1242         ENTRY;
1243
1244         oc = capa_lookup(dev->od_capa_hash, capa, 0);
1245         if (oc) {
1246                 if (capa_is_expired(oc)) {
1247                         DEBUG_CAPA(D_ERROR, capa, "expired");
1248                         rc = -ESTALE;
1249                 }
1250                 capa_put(oc);
1251                 RETURN(rc);
1252         }
1253
1254         if (capa_is_expired_sec(capa)) {
1255                 DEBUG_CAPA(D_ERROR, capa, "expired");
1256                 RETURN(-ESTALE);
1257         }
1258
1259         cfs_spin_lock(&capa_lock);
1260         for (i = 0; i < 2; i++) {
1261                 if (keys[i].lk_keyid == capa->lc_keyid) {
1262                         oti->oti_capa_key = keys[i];
1263                         break;
1264                 }
1265         }
1266         cfs_spin_unlock(&capa_lock);
1267
1268         if (i == 2) {
1269                 DEBUG_CAPA(D_ERROR, capa, "no matched capa key");
1270                 RETURN(-ESTALE);
1271         }
1272
1273         rc = capa_hmac(tcapa->lc_hmac, capa, oti->oti_capa_key.lk_key);
1274         if (rc)
1275                 RETURN(rc);
1276
1277         if (memcmp(tcapa->lc_hmac, capa->lc_hmac, sizeof(capa->lc_hmac))) {
1278                 DEBUG_CAPA(D_ERROR, capa, "HMAC mismatch");
1279                 RETURN(-EACCES);
1280         }
1281
1282         oc = capa_add(dev->od_capa_hash, capa);
1283         capa_put(oc);
1284
1285         RETURN(0);
1286 }
1287
1288 int osd_object_auth(const struct lu_env *env, struct dt_object *dt,
1289                     struct lustre_capa *capa, __u64 opc)
1290 {
1291         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
1292         struct osd_device *dev = osd_dev(dt->do_lu.lo_dev);
1293         struct md_capainfo *ci;
1294         int rc;
1295
1296         if (!dev->od_fl_capa)
1297                 return 0;
1298
1299         if (capa == BYPASS_CAPA)
1300                 return 0;
1301
1302         ci = md_capainfo(env);
1303         if (unlikely(!ci))
1304                 return 0;
1305
1306         if (ci->mc_auth == LC_ID_NONE)
1307                 return 0;
1308
1309         if (!capa) {
1310                 CERROR("no capability is provided for fid "DFID"\n", PFID(fid));
1311                 return -EACCES;
1312         }
1313
1314         if (!lu_fid_eq(fid, &capa->lc_fid)) {
1315                 DEBUG_CAPA(D_ERROR, capa, "fid "DFID" mismatch with",
1316                            PFID(fid));
1317                 return -EACCES;
1318         }
1319
1320         if (!capa_opc_supported(capa, opc)) {
1321                 DEBUG_CAPA(D_ERROR, capa, "opc "LPX64" not supported by", opc);
1322                 return -EACCES;
1323         }
1324
1325         if ((rc = capa_is_sane(env, dev, capa, dev->od_capa_keys))) {
1326                 DEBUG_CAPA(D_ERROR, capa, "insane (rc %d)", rc);
1327                 return -EACCES;
1328         }
1329
1330         return 0;
1331 }
1332
1333 static struct timespec *osd_inode_time(const struct lu_env *env,
1334                                        struct inode *inode, __u64 seconds)
1335 {
1336         struct osd_thread_info  *oti = osd_oti_get(env);
1337         struct timespec         *t   = &oti->oti_time;
1338
1339         t->tv_sec = seconds;
1340         t->tv_nsec = 0;
1341         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
1342         return t;
1343 }
1344
1345
1346 static void osd_inode_getattr(const struct lu_env *env,
1347                               struct inode *inode, struct lu_attr *attr)
1348 {
1349         attr->la_valid      |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
1350                                LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
1351                                LA_FLAGS | LA_NLINK | LA_RDEV | LA_BLKSIZE;
1352
1353         attr->la_atime      = LTIME_S(inode->i_atime);
1354         attr->la_mtime      = LTIME_S(inode->i_mtime);
1355         attr->la_ctime      = LTIME_S(inode->i_ctime);
1356         attr->la_mode       = inode->i_mode;
1357         attr->la_size       = i_size_read(inode);
1358         attr->la_blocks     = inode->i_blocks;
1359         attr->la_uid        = inode->i_uid;
1360         attr->la_gid        = inode->i_gid;
1361         attr->la_flags      = LDISKFS_I(inode)->i_flags;
1362         attr->la_nlink      = inode->i_nlink;
1363         attr->la_rdev       = inode->i_rdev;
1364         attr->la_blksize    = 1 << inode->i_blkbits;
1365         attr->la_blkbits    = inode->i_blkbits;
1366 }
1367
1368 static int osd_attr_get(const struct lu_env *env,
1369                         struct dt_object *dt,
1370                         struct lu_attr *attr,
1371                         struct lustre_capa *capa)
1372 {
1373         struct osd_object *obj = osd_dt_obj(dt);
1374
1375         LASSERT(dt_object_exists(dt));
1376         LINVRNT(osd_invariant(obj));
1377
1378         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
1379                 return -EACCES;
1380
1381         cfs_spin_lock(&obj->oo_guard);
1382         osd_inode_getattr(env, obj->oo_inode, attr);
1383         cfs_spin_unlock(&obj->oo_guard);
1384         return 0;
1385 }
1386
1387 static int osd_declare_attr_set(const struct lu_env *env,
1388                                 struct dt_object *dt,
1389                                 const struct lu_attr *attr,
1390                                 struct thandle *handle)
1391 {
1392         struct osd_thandle     *oh;
1393         struct osd_object      *obj;
1394         struct osd_thread_info *info = osd_oti_get(env);
1395         struct lquota_id_info  *qi = &info->oti_qi;
1396         long long               bspace;
1397         int                     rc = 0;
1398         bool                    allocated;
1399         ENTRY;
1400
1401         LASSERT(dt != NULL);
1402         LASSERT(handle != NULL);
1403
1404         obj = osd_dt_obj(dt);
1405         LASSERT(osd_invariant(obj));
1406
1407         oh = container_of0(handle, struct osd_thandle, ot_super);
1408         LASSERT(oh->ot_handle == NULL);
1409
1410         OSD_DECLARE_OP(oh, attr_set);
1411         oh->ot_credits += osd_dto_credits_noquota[DTO_ATTR_SET_BASE];
1412
1413         if (attr == NULL || obj->oo_inode == NULL)
1414                 RETURN(rc);
1415
1416         bspace   = obj->oo_inode->i_blocks;
1417         bspace <<= obj->oo_inode->i_sb->s_blocksize_bits;
1418         bspace   = toqb(bspace);
1419
1420         /* Changing ownership is always preformed by super user, it should not
1421          * fail with EDQUOT.
1422          *
1423          * We still need to call the osd_declare_qid() to calculate the journal
1424          * credits for updating quota accounting files and to trigger quota
1425          * space adjustment once the operation is completed.*/
1426         if ((attr->la_valid & LA_UID) != 0 &&
1427              attr->la_uid != obj->oo_inode->i_uid) {
1428                 qi->lqi_type = USRQUOTA;
1429
1430                 /* inode accounting */
1431                 qi->lqi_is_blk = false;
1432
1433                 /* one more inode for the new owner ... */
1434                 qi->lqi_id.qid_uid = attr->la_uid;
1435                 qi->lqi_space      = 1;
1436                 allocated = (attr->la_uid == 0) ? true : false;
1437                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1438                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1439                         rc = 0;
1440                 if (rc)
1441                         RETURN(rc);
1442
1443                 /* and one less inode for the current uid */
1444                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1445                 qi->lqi_space      = -1;
1446                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1447                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1448                         rc = 0;
1449                 if (rc)
1450                         RETURN(rc);
1451
1452                 /* block accounting */
1453                 qi->lqi_is_blk = true;
1454
1455                 /* more blocks for the new owner ... */
1456                 qi->lqi_id.qid_uid = attr->la_uid;
1457                 qi->lqi_space      = bspace;
1458                 allocated = (attr->la_uid == 0) ? true : false;
1459                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1460                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1461                         rc = 0;
1462                 if (rc)
1463                         RETURN(rc);
1464
1465                 /* and finally less blocks for the current owner */
1466                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1467                 qi->lqi_space      = -bspace;
1468                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1469                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1470                         rc = 0;
1471                 if (rc)
1472                         RETURN(rc);
1473         }
1474
1475         if (attr->la_valid & LA_GID &&
1476             attr->la_gid != obj->oo_inode->i_gid) {
1477                 qi->lqi_type = GRPQUOTA;
1478
1479                 /* inode accounting */
1480                 qi->lqi_is_blk = false;
1481
1482                 /* one more inode for the new group owner ... */
1483                 qi->lqi_id.qid_gid = attr->la_gid;
1484                 qi->lqi_space      = 1;
1485                 allocated = (attr->la_gid == 0) ? true : false;
1486                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1487                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1488                         rc = 0;
1489                 if (rc)
1490                         RETURN(rc);
1491
1492                 /* and one less inode for the current gid */
1493                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1494                 qi->lqi_space      = -1;
1495                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1496                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1497                         rc = 0;
1498                 if (rc)
1499                         RETURN(rc);
1500
1501                 /* block accounting */
1502                 qi->lqi_is_blk = true;
1503
1504                 /* more blocks for the new owner ... */
1505                 qi->lqi_id.qid_gid = attr->la_gid;
1506                 qi->lqi_space      = bspace;
1507                 allocated = (attr->la_gid == 0) ? true : false;
1508                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1509                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1510                         rc = 0;
1511                 if (rc)
1512                         RETURN(rc);
1513
1514                 /* and finally less blocks for the current owner */
1515                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1516                 qi->lqi_space      = -bspace;
1517                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1518                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1519                         rc = 0;
1520                 if (rc)
1521                         RETURN(rc);
1522         }
1523
1524         RETURN(rc);
1525 }
1526
1527 static int osd_inode_setattr(const struct lu_env *env,
1528                              struct inode *inode, const struct lu_attr *attr)
1529 {
1530         __u64 bits;
1531
1532         bits = attr->la_valid;
1533
1534         LASSERT(!(bits & LA_TYPE)); /* Huh? You want too much. */
1535
1536         if (bits & LA_ATIME)
1537                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
1538         if (bits & LA_CTIME)
1539                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
1540         if (bits & LA_MTIME)
1541                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
1542         if (bits & LA_SIZE) {
1543                 LDISKFS_I(inode)->i_disksize = attr->la_size;
1544                 i_size_write(inode, attr->la_size);
1545         }
1546
1547 #if 0
1548         /* OSD should not change "i_blocks" which is used by quota.
1549          * "i_blocks" should be changed by ldiskfs only. */
1550         if (bits & LA_BLOCKS)
1551                 inode->i_blocks = attr->la_blocks;
1552 #endif
1553         if (bits & LA_MODE)
1554                 inode->i_mode   = (inode->i_mode & S_IFMT) |
1555                         (attr->la_mode & ~S_IFMT);
1556         if (bits & LA_UID)
1557                 inode->i_uid    = attr->la_uid;
1558         if (bits & LA_GID)
1559                 inode->i_gid    = attr->la_gid;
1560         if (bits & LA_NLINK)
1561                 inode->i_nlink  = attr->la_nlink;
1562         if (bits & LA_RDEV)
1563                 inode->i_rdev   = attr->la_rdev;
1564
1565         if (bits & LA_FLAGS) {
1566                 /* always keep S_NOCMTIME */
1567                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
1568                                  S_NOCMTIME;
1569         }
1570         return 0;
1571 }
1572
1573 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
1574 {
1575         if ((attr->la_valid & LA_UID && attr->la_uid != inode->i_uid) ||
1576             (attr->la_valid & LA_GID && attr->la_gid != inode->i_gid)) {
1577                 struct iattr    iattr;
1578                 int             rc;
1579
1580                 iattr.ia_valid = 0;
1581                 if (attr->la_valid & LA_UID)
1582                         iattr.ia_valid |= ATTR_UID;
1583                 if (attr->la_valid & LA_GID)
1584                         iattr.ia_valid |= ATTR_GID;
1585                 iattr.ia_uid = attr->la_uid;
1586                 iattr.ia_gid = attr->la_gid;
1587
1588                 rc = ll_vfs_dq_transfer(inode, &iattr);
1589                 if (rc) {
1590                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
1591                                "enforcement enabled on the ldiskfs filesystem?",
1592                                inode->i_sb->s_id, rc);
1593                         return rc;
1594                 }
1595         }
1596         return 0;
1597 }
1598
1599 static int osd_attr_set(const struct lu_env *env,
1600                         struct dt_object *dt,
1601                         const struct lu_attr *attr,
1602                         struct thandle *handle,
1603                         struct lustre_capa *capa)
1604 {
1605         struct osd_object *obj = osd_dt_obj(dt);
1606         struct inode      *inode;
1607         int rc;
1608
1609         LASSERT(handle != NULL);
1610         LASSERT(dt_object_exists(dt));
1611         LASSERT(osd_invariant(obj));
1612
1613         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
1614                 return -EACCES;
1615
1616         OSD_EXEC_OP(handle, attr_set);
1617
1618         inode = obj->oo_inode;
1619         if (!osd_dt_dev(handle->th_dev)->od_is_md) {
1620                 /* OFD support */
1621                 rc = osd_quota_transfer(inode, attr);
1622                 if (rc)
1623                         return rc;
1624         } else {
1625 #ifdef HAVE_QUOTA_SUPPORT
1626                 if ((attr->la_valid & LA_UID && attr->la_uid != inode->i_uid) ||
1627                     (attr->la_valid & LA_GID && attr->la_gid != inode->i_gid)) {
1628                         struct osd_ctxt *save = &osd_oti_get(env)->oti_ctxt;
1629                         struct           iattr iattr;
1630                         int              rc;
1631
1632                         iattr.ia_valid = 0;
1633                         if (attr->la_valid & LA_UID)
1634                                 iattr.ia_valid |= ATTR_UID;
1635                         if (attr->la_valid & LA_GID)
1636                                 iattr.ia_valid |= ATTR_GID;
1637                         iattr.ia_uid = attr->la_uid;
1638                         iattr.ia_gid = attr->la_gid;
1639                         osd_push_ctxt(env, save, 1);
1640                         rc = ll_vfs_dq_transfer(inode, &iattr) ? -EDQUOT : 0;
1641                         osd_pop_ctxt(save, 1);
1642                         if (rc != 0)
1643                                 return rc;
1644                 }
1645 #endif
1646         }
1647         cfs_spin_lock(&obj->oo_guard);
1648         rc = osd_inode_setattr(env, inode, attr);
1649         cfs_spin_unlock(&obj->oo_guard);
1650
1651         if (!rc)
1652                 inode->i_sb->s_op->dirty_inode(inode);
1653         return rc;
1654 }
1655
1656 struct dentry *osd_child_dentry_get(const struct lu_env *env,
1657                                     struct osd_object *obj,
1658                                     const char *name, const int namelen)
1659 {
1660         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
1661 }
1662
1663 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
1664                       cfs_umode_t mode,
1665                       struct dt_allocation_hint *hint,
1666                       struct thandle *th)
1667 {
1668         int result;
1669         struct osd_device  *osd = osd_obj2dev(obj);
1670         struct osd_thandle *oth;
1671         struct dt_object   *parent = NULL;
1672         struct inode       *inode;
1673 #ifdef HAVE_QUOTA_SUPPORT
1674         struct osd_ctxt    *save = &info->oti_ctxt;
1675 #endif
1676
1677         LINVRNT(osd_invariant(obj));
1678         LASSERT(obj->oo_inode == NULL);
1679         LASSERT(obj->oo_hl_head == NULL);
1680
1681         if (S_ISDIR(mode) && ldiskfs_pdo) {
1682                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1683                 if (obj->oo_hl_head == NULL)
1684                         return -ENOMEM;
1685         }
1686
1687         oth = container_of(th, struct osd_thandle, ot_super);
1688         LASSERT(oth->ot_handle->h_transaction != NULL);
1689
1690         if (hint && hint->dah_parent)
1691                 parent = hint->dah_parent;
1692
1693 #ifdef HAVE_QUOTA_SUPPORT
1694         osd_push_ctxt(info->oti_env, save, osd_dt_dev(th->th_dev)->od_is_md);
1695 #endif
1696         inode = ldiskfs_create_inode(oth->ot_handle,
1697                                      parent ? osd_dt_obj(parent)->oo_inode :
1698                                               osd_sb(osd)->s_root->d_inode,
1699                                      mode);
1700 #ifdef HAVE_QUOTA_SUPPORT
1701         osd_pop_ctxt(save, osd_dt_dev(th->th_dev)->od_is_md);
1702 #endif
1703         if (!IS_ERR(inode)) {
1704                 /* Do not update file c/mtime in ldiskfs.
1705                  * NB: don't need any lock because no contention at this
1706                  * early stage */
1707                 inode->i_flags |= S_NOCMTIME;
1708                 inode->i_state |= I_LUSTRE_NOSCRUB;
1709                 obj->oo_inode = inode;
1710                 result = 0;
1711         } else {
1712                 if (obj->oo_hl_head != NULL) {
1713                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1714                         obj->oo_hl_head = NULL;
1715                 }
1716                 result = PTR_ERR(inode);
1717         }
1718         LINVRNT(osd_invariant(obj));
1719         return result;
1720 }
1721
1722 enum {
1723         OSD_NAME_LEN = 255
1724 };
1725
1726 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
1727                      struct lu_attr *attr,
1728                      struct dt_allocation_hint *hint,
1729                      struct dt_object_format *dof,
1730                      struct thandle *th)
1731 {
1732         int result;
1733         struct osd_thandle *oth;
1734         struct osd_device *osd = osd_obj2dev(obj);
1735         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX));
1736
1737         LASSERT(S_ISDIR(attr->la_mode));
1738
1739         oth = container_of(th, struct osd_thandle, ot_super);
1740         LASSERT(oth->ot_handle->h_transaction != NULL);
1741         result = osd_mkfile(info, obj, mode, hint, th);
1742         if (result == 0 && osd->od_iop_mode == 0) {
1743                 LASSERT(obj->oo_inode != NULL);
1744                 /*
1745                  * XXX uh-oh... call low-level iam function directly.
1746                  */
1747
1748                 result = iam_lvar_create(obj->oo_inode, OSD_NAME_LEN, 4,
1749                                          sizeof (struct osd_fid_pack),
1750                                          oth->ot_handle);
1751         }
1752         return result;
1753 }
1754
1755 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
1756                         struct lu_attr *attr,
1757                         struct dt_allocation_hint *hint,
1758                         struct dt_object_format *dof,
1759                         struct thandle *th)
1760 {
1761         int result;
1762         struct osd_thandle *oth;
1763         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
1764
1765         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
1766
1767         LASSERT(S_ISREG(attr->la_mode));
1768
1769         oth = container_of(th, struct osd_thandle, ot_super);
1770         LASSERT(oth->ot_handle->h_transaction != NULL);
1771
1772         result = osd_mkfile(info, obj, mode, hint, th);
1773         if (result == 0) {
1774                 LASSERT(obj->oo_inode != NULL);
1775                 if (feat->dif_flags & DT_IND_VARKEY)
1776                         result = iam_lvar_create(obj->oo_inode,
1777                                                  feat->dif_keysize_max,
1778                                                  feat->dif_ptrsize,
1779                                                  feat->dif_recsize_max,
1780                                                  oth->ot_handle);
1781                 else
1782                         result = iam_lfix_create(obj->oo_inode,
1783                                                  feat->dif_keysize_max,
1784                                                  feat->dif_ptrsize,
1785                                                  feat->dif_recsize_max,
1786                                                  oth->ot_handle);
1787
1788         }
1789         return result;
1790 }
1791
1792 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
1793                      struct lu_attr *attr,
1794                      struct dt_allocation_hint *hint,
1795                      struct dt_object_format *dof,
1796                      struct thandle *th)
1797 {
1798         LASSERT(S_ISREG(attr->la_mode));
1799         return osd_mkfile(info, obj, (attr->la_mode &
1800                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
1801 }
1802
1803 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
1804                      struct lu_attr *attr,
1805                      struct dt_allocation_hint *hint,
1806                      struct dt_object_format *dof,
1807                      struct thandle *th)
1808 {
1809         LASSERT(S_ISLNK(attr->la_mode));
1810         return osd_mkfile(info, obj, (attr->la_mode &
1811                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
1812 }
1813
1814 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
1815                      struct lu_attr *attr,
1816                      struct dt_allocation_hint *hint,
1817                      struct dt_object_format *dof,
1818                      struct thandle *th)
1819 {
1820         cfs_umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
1821         int result;
1822
1823         LINVRNT(osd_invariant(obj));
1824         LASSERT(obj->oo_inode == NULL);
1825         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
1826                 S_ISFIFO(mode) || S_ISSOCK(mode));
1827
1828         result = osd_mkfile(info, obj, mode, hint, th);
1829         if (result == 0) {
1830                 LASSERT(obj->oo_inode != NULL);
1831                 /*
1832                  * This inode should be marked dirty for i_rdev.  Currently
1833                  * that is done in the osd_attr_init().
1834                  */
1835                 init_special_inode(obj->oo_inode, mode, attr->la_rdev);
1836         }
1837         LINVRNT(osd_invariant(obj));
1838         return result;
1839 }
1840
1841 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
1842                               struct lu_attr *,
1843                               struct dt_allocation_hint *hint,
1844                               struct dt_object_format *dof,
1845                               struct thandle *);
1846
1847 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
1848 {
1849         osd_obj_type_f result;
1850
1851         switch (type) {
1852         case DFT_DIR:
1853                 result = osd_mkdir;
1854                 break;
1855         case DFT_REGULAR:
1856                 result = osd_mkreg;
1857                 break;
1858         case DFT_SYM:
1859                 result = osd_mksym;
1860                 break;
1861         case DFT_NODE:
1862                 result = osd_mknod;
1863                 break;
1864         case DFT_INDEX:
1865                 result = osd_mk_index;
1866                 break;
1867
1868         default:
1869                 LBUG();
1870                 break;
1871         }
1872         return result;
1873 }
1874
1875
1876 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
1877                         struct dt_object *parent, struct dt_object *child,
1878                         cfs_umode_t child_mode)
1879 {
1880         LASSERT(ah);
1881
1882         memset(ah, 0, sizeof(*ah));
1883         ah->dah_parent = parent;
1884         ah->dah_mode = child_mode;
1885 }
1886
1887 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
1888                           struct lu_attr *attr, struct dt_object_format *dof)
1889 {
1890         struct inode   *inode = obj->oo_inode;
1891         __u64           valid = attr->la_valid;
1892         int             result;
1893
1894         attr->la_valid &= ~(LA_TYPE | LA_MODE);
1895
1896         if (dof->dof_type != DFT_NODE)
1897                 attr->la_valid &= ~LA_RDEV;
1898         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
1899                 attr->la_valid &= ~LA_ATIME;
1900         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
1901                 attr->la_valid &= ~LA_CTIME;
1902         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
1903                 attr->la_valid &= ~LA_MTIME;
1904
1905         if (!osd_obj2dev(obj)->od_is_md) {
1906                 /* OFD support */
1907                 result = osd_quota_transfer(inode, attr);
1908                 if (result)
1909                         return;
1910         } else {
1911 #ifdef HAVE_QUOTA_SUPPORT
1912                 attr->la_valid &= ~(LA_UID | LA_GID);
1913 #endif
1914         }
1915
1916         if (attr->la_valid != 0) {
1917                 result = osd_inode_setattr(info->oti_env, inode, attr);
1918                 /*
1919                  * The osd_inode_setattr() should always succeed here.  The
1920                  * only error that could be returned is EDQUOT when we are
1921                  * trying to change the UID or GID of the inode. However, this
1922                  * should not happen since quota enforcement is no longer
1923                  * enabled on ldiskfs (lquota takes care of it).
1924                  */
1925                 LASSERTF(result == 0, "%d", result);
1926                 inode->i_sb->s_op->dirty_inode(inode);
1927         }
1928
1929         attr->la_valid = valid;
1930 }
1931
1932 /**
1933  * Helper function for osd_object_create()
1934  *
1935  * \retval 0, on success
1936  */
1937 static int __osd_object_create(struct osd_thread_info *info,
1938                                struct osd_object *obj, struct lu_attr *attr,
1939                                struct dt_allocation_hint *hint,
1940                                struct dt_object_format *dof,
1941                                struct thandle *th)
1942 {
1943         int     result;
1944         __u32   umask;
1945
1946         /* we drop umask so that permissions we pass are not affected */
1947         umask = current->fs->umask;
1948         current->fs->umask = 0;
1949
1950         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
1951                                                   th);
1952         if (result == 0) {
1953                 osd_attr_init(info, obj, attr, dof);
1954                 osd_object_init0(obj);
1955                 /* bz 24037 */
1956                 if (obj->oo_inode && (obj->oo_inode->i_state & I_NEW))
1957                         unlock_new_inode(obj->oo_inode);
1958         }
1959
1960         /* restore previous umask value */
1961         current->fs->umask = umask;
1962
1963         return result;
1964 }
1965
1966 /**
1967  * Helper function for osd_object_create()
1968  *
1969  * \retval 0, on success
1970  */
1971 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
1972                            const struct lu_fid *fid, struct thandle *th)
1973 {
1974         struct osd_thread_info *info = osd_oti_get(env);
1975         struct osd_inode_id    *id   = &info->oti_id;
1976         struct osd_device      *osd  = osd_obj2dev(obj);
1977
1978         LASSERT(obj->oo_inode != NULL);
1979
1980         if (osd->od_is_md) {
1981                 struct md_ucred *uc = md_ucred(env);
1982                 LASSERT(uc != NULL);
1983         }
1984
1985         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
1986         return osd_oi_insert(info, osd, fid, id, th);
1987 }
1988
1989 static int osd_declare_object_create(const struct lu_env *env,
1990                                      struct dt_object *dt,
1991                                      struct lu_attr *attr,
1992                                      struct dt_allocation_hint *hint,
1993                                      struct dt_object_format *dof,
1994                                      struct thandle *handle)
1995 {
1996         struct osd_thandle      *oh;
1997         int                      rc;
1998         ENTRY;
1999
2000         LASSERT(handle != NULL);
2001
2002         oh = container_of0(handle, struct osd_thandle, ot_super);
2003         LASSERT(oh->ot_handle == NULL);
2004
2005         OSD_DECLARE_OP(oh, create);
2006         oh->ot_credits += osd_dto_credits_noquota[DTO_OBJECT_CREATE];
2007         /* XXX: So far, only normal fid needs be inserted into the oi,
2008          *      things could be changed later. Revise following code then. */
2009         if (fid_is_norm(lu_object_fid(&dt->do_lu))) {
2010                 OSD_DECLARE_OP(oh, insert);
2011                 oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
2012                 /* Reuse idle OI block may cause additional one OI block
2013                  * to be changed. */
2014                 oh->ot_credits += 1;
2015         }
2016         /* If this is directory, then we expect . and .. to be inserted as
2017          * well. The one directory block always needs to be created for the
2018          * directory, so we could use DTO_WRITE_BASE here (GDT, block bitmap,
2019          * block), there is no danger of needing a tree for the first block.
2020          */
2021         if (attr && S_ISDIR(attr->la_mode)) {
2022                 OSD_DECLARE_OP(oh, insert);
2023                 OSD_DECLARE_OP(oh, insert);
2024                 oh->ot_credits += osd_dto_credits_noquota[DTO_WRITE_BASE];
2025         }
2026
2027         if (!attr)
2028                 RETURN(0);
2029
2030         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid, 1, oh,
2031                                    false, false, NULL, false);
2032         RETURN(rc);
2033 }
2034
2035 static int osd_object_create(const struct lu_env *env, struct dt_object *dt,
2036                              struct lu_attr *attr,
2037                              struct dt_allocation_hint *hint,
2038                              struct dt_object_format *dof,
2039                              struct thandle *th)
2040 {
2041         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2042         struct osd_object      *obj    = osd_dt_obj(dt);
2043         struct osd_thread_info *info   = osd_oti_get(env);
2044         int result;
2045
2046         ENTRY;
2047
2048         LINVRNT(osd_invariant(obj));
2049         LASSERT(!dt_object_exists(dt));
2050         LASSERT(osd_write_locked(env, obj));
2051         LASSERT(th != NULL);
2052
2053         if (unlikely(fid_is_acct(fid)))
2054                 /* Quota files can't be created from the kernel any more,
2055                  * 'tune2fs -O quota' will take care of creating them */
2056                 RETURN(-EPERM);
2057
2058         OSD_EXEC_OP(th, create);
2059
2060         result = __osd_object_create(info, obj, attr, hint, dof, th);
2061         if (result == 0)
2062                 result = __osd_oi_insert(env, obj, fid, th);
2063
2064         LASSERT(ergo(result == 0, dt_object_exists(dt)));
2065         LASSERT(osd_invariant(obj));
2066         RETURN(result);
2067 }
2068
2069 /**
2070  * Called to destroy on-disk representation of the object
2071  *
2072  * Concurrency: must be locked
2073  */
2074 static int osd_declare_object_destroy(const struct lu_env *env,
2075                                       struct dt_object *dt,
2076                                       struct thandle *th)
2077 {
2078         struct osd_object  *obj = osd_dt_obj(dt);
2079         struct inode       *inode = obj->oo_inode;
2080         struct osd_thandle *oh;
2081         int                 rc;
2082         ENTRY;
2083
2084         oh = container_of0(th, struct osd_thandle, ot_super);
2085         LASSERT(oh->ot_handle == NULL);
2086         LASSERT(inode);
2087
2088         OSD_DECLARE_OP(oh, destroy);
2089         OSD_DECLARE_OP(oh, delete);
2090         oh->ot_credits += osd_dto_credits_noquota[DTO_OBJECT_DELETE];
2091         /* XXX: So far, only normal fid needs to be inserted into the OI,
2092          *      so only normal fid needs to be removed from the OI also. */
2093         if (fid_is_norm(lu_object_fid(&dt->do_lu))) {
2094                 oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
2095                 /* Recycle idle OI leaf may cause additional three OI blocks
2096                  * to be changed. */
2097                 oh->ot_credits += 3;
2098         }
2099
2100         /* one less inode */
2101         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, -1, oh,
2102                                    false, true, NULL, false);
2103         if (rc)
2104                 RETURN(rc);
2105         /* data to be truncated */
2106         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh, true,
2107                                    true, NULL, false);
2108         RETURN(rc);
2109 }
2110
2111 static int osd_object_destroy(const struct lu_env *env,
2112                               struct dt_object *dt,
2113                               struct thandle *th)
2114 {
2115         const struct lu_fid    *fid = lu_object_fid(&dt->do_lu);
2116         struct osd_object      *obj = osd_dt_obj(dt);
2117         struct inode           *inode = obj->oo_inode;
2118         struct osd_device      *osd = osd_obj2dev(obj);
2119         struct osd_thandle     *oh;
2120         int                     result;
2121         ENTRY;
2122
2123         oh = container_of0(th, struct osd_thandle, ot_super);
2124         LASSERT(oh->ot_handle);
2125         LASSERT(inode);
2126         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
2127
2128         if (unlikely(fid_is_acct(fid)))
2129                 RETURN(-EPERM);
2130
2131         /* Parallel control for OI scrub. For most of cases, there is no
2132          * lock contention. So it will not affect unlink performance. */
2133         cfs_mutex_lock(&inode->i_mutex);
2134         if (S_ISDIR(inode->i_mode)) {
2135                 LASSERT(osd_inode_unlinked(inode) ||
2136                         inode->i_nlink == 1);
2137                 cfs_spin_lock(&obj->oo_guard);
2138                 inode->i_nlink = 0;
2139                 cfs_spin_unlock(&obj->oo_guard);
2140                 inode->i_sb->s_op->dirty_inode(inode);
2141         } else {
2142                 LASSERT(osd_inode_unlinked(inode));
2143         }
2144
2145         OSD_EXEC_OP(th, destroy);
2146
2147         result = osd_oi_delete(osd_oti_get(env), osd, fid, th);
2148         cfs_mutex_unlock(&inode->i_mutex);
2149
2150         /* XXX: add to ext3 orphan list */
2151         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
2152
2153         /* not needed in the cache anymore */
2154         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
2155
2156         RETURN(0);
2157 }
2158
2159 /**
2160  * Helper function for osd_xattr_set()
2161  */
2162 static int __osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
2163                            const struct lu_buf *buf, const char *name, int fl)
2164 {
2165         struct osd_object      *obj      = osd_dt_obj(dt);
2166         struct inode           *inode    = obj->oo_inode;
2167         struct osd_thread_info *info     = osd_oti_get(env);
2168         struct dentry          *dentry   = &info->oti_child_dentry;
2169         int                     fs_flags = 0;
2170         int                     rc;
2171
2172         LASSERT(dt_object_exists(dt));
2173         LASSERT(inode->i_op != NULL && inode->i_op->setxattr != NULL);
2174
2175         if (fl & LU_XATTR_REPLACE)
2176                 fs_flags |= XATTR_REPLACE;
2177
2178         if (fl & LU_XATTR_CREATE)
2179                 fs_flags |= XATTR_CREATE;
2180
2181         dentry->d_inode = inode;
2182         rc = inode->i_op->setxattr(dentry, name, buf->lb_buf,
2183                                    buf->lb_len, fs_flags);
2184         return rc;
2185 }
2186
2187 /**
2188  * Put the fid into lustre_mdt_attrs, and then place the structure
2189  * inode's ea. This fid should not be altered during the life time
2190  * of the inode.
2191  *
2192  * \retval +ve, on success
2193  * \retval -ve, on error
2194  *
2195  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
2196  */
2197 static int osd_ea_fid_set(const struct lu_env *env, struct dt_object *dt,
2198                           const struct lu_fid *fid)
2199 {
2200         struct osd_thread_info  *info      = osd_oti_get(env);
2201         struct lustre_mdt_attrs *mdt_attrs = &info->oti_mdt_attrs;
2202
2203         lustre_lma_init(mdt_attrs, fid);
2204         lustre_lma_swab(mdt_attrs);
2205         return __osd_xattr_set(env, dt,
2206                                osd_buf_get(env, mdt_attrs, sizeof *mdt_attrs),
2207                                XATTR_NAME_LMA, LU_XATTR_CREATE);
2208
2209 }
2210
2211 /**
2212  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
2213  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
2214  * To have compatilibility with 1.8 ldiskfs driver we need to have
2215  * magic number at start of fid data.
2216  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
2217  * its inmemory API.
2218  */
2219 void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
2220                                   const struct dt_rec *fid)
2221 {
2222         param->edp_magic = LDISKFS_LUFID_MAGIC;
2223         param->edp_len =  sizeof(struct lu_fid) + 1;
2224
2225         fid_cpu_to_be((struct lu_fid *)param->edp_data,
2226                       (struct lu_fid *)fid);
2227 }
2228
2229 /**
2230  * Try to read the fid from inode ea into dt_rec, if return value
2231  * i.e. rc is +ve, then we got fid, otherwise we will have to form igif
2232  *
2233  * \param fid object fid.
2234  *
2235  * \retval 0 on success
2236  */
2237 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
2238                           __u32 ino, struct lu_fid *fid,
2239                           struct osd_inode_id *id)
2240 {
2241         struct osd_thread_info *info  = osd_oti_get(env);
2242         struct inode           *inode;
2243         ENTRY;
2244
2245         osd_id_gen(id, ino, OSD_OII_NOGEN);
2246         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
2247         if (IS_ERR(inode))
2248                 RETURN(PTR_ERR(inode));
2249
2250         iput(inode);
2251         RETURN(0);
2252 }
2253
2254 /**
2255  * OSD layer object create function for interoperability mode (b11826).
2256  * This is mostly similar to osd_object_create(). Only difference being, fid is
2257  * inserted into inode ea here.
2258  *
2259  * \retval   0, on success
2260  * \retval -ve, on error
2261  */
2262 static int osd_object_ea_create(const struct lu_env *env, struct dt_object *dt,
2263                                 struct lu_attr *attr,
2264                                 struct dt_allocation_hint *hint,
2265                                 struct dt_object_format *dof,
2266                                 struct thandle *th)
2267 {
2268         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2269         struct osd_object      *obj    = osd_dt_obj(dt);
2270         struct osd_thread_info *info   = osd_oti_get(env);
2271         int                     result;
2272
2273         ENTRY;
2274
2275         LASSERT(osd_invariant(obj));
2276         LASSERT(!dt_object_exists(dt));
2277         LASSERT(osd_write_locked(env, obj));
2278         LASSERT(th != NULL);
2279
2280         if (unlikely(fid_is_acct(fid)))
2281                 /* Quota files can't be created from the kernel any more,
2282                  * 'tune2fs -O quota' will take care of creating them */
2283                 RETURN(-EPERM);
2284
2285         OSD_EXEC_OP(th, create);
2286
2287         result = __osd_object_create(info, obj, attr, hint, dof, th);
2288         /* objects under osd root shld have igif fid, so dont add fid EA */
2289         if (result == 0 && fid_seq(fid) >= FID_SEQ_NORMAL)
2290                 result = osd_ea_fid_set(env, dt, fid);
2291
2292         if (result == 0)
2293                 result = __osd_oi_insert(env, obj, fid, th);
2294
2295         LASSERT(ergo(result == 0, dt_object_exists(dt)));
2296         LINVRNT(osd_invariant(obj));
2297         RETURN(result);
2298 }
2299
2300 static int osd_declare_object_ref_add(const struct lu_env *env,
2301                                       struct dt_object *dt,
2302                                       struct thandle *handle)
2303 {
2304         struct osd_thandle *oh;
2305
2306         /* it's possible that object doesn't exist yet */
2307         LASSERT(handle != NULL);
2308
2309         oh = container_of0(handle, struct osd_thandle, ot_super);
2310         LASSERT(oh->ot_handle == NULL);
2311
2312         OSD_DECLARE_OP(oh, ref_add);
2313         oh->ot_credits += osd_dto_credits_noquota[DTO_ATTR_SET_BASE];
2314
2315         return 0;
2316 }
2317
2318 /*
2319  * Concurrency: @dt is write locked.
2320  */
2321 static int osd_object_ref_add(const struct lu_env *env,
2322                               struct dt_object *dt, struct thandle *th)
2323 {
2324         struct osd_object *obj = osd_dt_obj(dt);
2325         struct inode      *inode = obj->oo_inode;
2326
2327         LINVRNT(osd_invariant(obj));
2328         LASSERT(dt_object_exists(dt));
2329         LASSERT(osd_write_locked(env, obj));
2330         LASSERT(th != NULL);
2331
2332         OSD_EXEC_OP(th, ref_add);
2333
2334         /*
2335          * DIR_NLINK feature is set for compatibility reasons if:
2336          * 1) nlinks > LDISKFS_LINK_MAX, or
2337          * 2) nlinks == 2, since this indicates i_nlink was previously 1.
2338          *
2339          * It is easier to always set this flag (rather than check and set),
2340          * since it has less overhead, and the superblock will be dirtied
2341          * at some point. Both e2fsprogs and any Lustre-supported ldiskfs
2342          * do not actually care whether this flag is set or not.
2343          */
2344         cfs_spin_lock(&obj->oo_guard);
2345         inode->i_nlink++;
2346         if (S_ISDIR(inode->i_mode) && inode->i_nlink > 1) {
2347                 if (inode->i_nlink >= LDISKFS_LINK_MAX ||
2348                     inode->i_nlink == 2)
2349                         inode->i_nlink = 1;
2350         }
2351         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
2352         cfs_spin_unlock(&obj->oo_guard);
2353         inode->i_sb->s_op->dirty_inode(inode);
2354         LINVRNT(osd_invariant(obj));
2355
2356         return 0;
2357 }
2358
2359 static int osd_declare_object_ref_del(const struct lu_env *env,
2360                                       struct dt_object *dt,
2361                                       struct thandle *handle)
2362 {
2363         struct osd_thandle *oh;
2364
2365         LASSERT(dt_object_exists(dt));
2366         LASSERT(handle != NULL);
2367
2368         oh = container_of0(handle, struct osd_thandle, ot_super);
2369         LASSERT(oh->ot_handle == NULL);
2370
2371         OSD_DECLARE_OP(oh, ref_del);
2372         oh->ot_credits += osd_dto_credits_noquota[DTO_ATTR_SET_BASE];
2373
2374         return 0;
2375 }
2376
2377 /*
2378  * Concurrency: @dt is write locked.
2379  */
2380 static int osd_object_ref_del(const struct lu_env *env, struct dt_object *dt,
2381                               struct thandle *th)
2382 {
2383         struct osd_object *obj = osd_dt_obj(dt);
2384         struct inode      *inode = obj->oo_inode;
2385
2386         LINVRNT(osd_invariant(obj));
2387         LASSERT(dt_object_exists(dt));
2388         LASSERT(osd_write_locked(env, obj));
2389         LASSERT(th != NULL);
2390
2391         OSD_EXEC_OP(th, ref_del);
2392
2393         cfs_spin_lock(&obj->oo_guard);
2394         LASSERT(inode->i_nlink > 0);
2395         inode->i_nlink--;
2396         /* If this is/was a many-subdir directory (nlink > LDISKFS_LINK_MAX)
2397          * then the nlink count is 1. Don't let it be set to 0 or the directory
2398          * inode will be deleted incorrectly. */
2399         if (S_ISDIR(inode->i_mode) && inode->i_nlink == 0)
2400                 inode->i_nlink++;
2401         cfs_spin_unlock(&obj->oo_guard);
2402         inode->i_sb->s_op->dirty_inode(inode);
2403         LINVRNT(osd_invariant(obj));
2404
2405         return 0;
2406 }
2407
2408 /*
2409  * Get the 64-bit version for an inode.
2410  */
2411 static int osd_object_version_get(const struct lu_env *env,
2412                                   struct dt_object *dt, dt_obj_version_t *ver)
2413 {
2414         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2415
2416         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
2417                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2418         *ver = LDISKFS_I(inode)->i_fs_version;
2419         return 0;
2420 }
2421
2422 /*
2423  * Concurrency: @dt is read locked.
2424  */
2425 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
2426                          struct lu_buf *buf, const char *name,
2427                          struct lustre_capa *capa)
2428 {
2429         struct osd_object      *obj    = osd_dt_obj(dt);
2430         struct inode           *inode  = obj->oo_inode;
2431         struct osd_thread_info *info   = osd_oti_get(env);
2432         struct dentry          *dentry = &info->oti_obj_dentry;
2433
2434         /* version get is not real XATTR but uses xattr API */
2435         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2436                 /* for version we are just using xattr API but change inode
2437                  * field instead */
2438                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2439                 osd_object_version_get(env, dt, buf->lb_buf);
2440                 return sizeof(dt_obj_version_t);
2441         }
2442
2443         LASSERT(dt_object_exists(dt));
2444         LASSERT(inode->i_op != NULL && inode->i_op->getxattr != NULL);
2445
2446         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2447                 return -EACCES;
2448
2449         dentry->d_inode = inode;
2450         return inode->i_op->getxattr(dentry, name, buf->lb_buf, buf->lb_len);
2451 }
2452
2453
2454 static int osd_declare_xattr_set(const struct lu_env *env,
2455                                  struct dt_object *dt,
2456                                  const struct lu_buf *buf, const char *name,
2457                                  int fl, struct thandle *handle)
2458 {
2459         struct osd_thandle *oh;
2460
2461         LASSERT(handle != NULL);
2462
2463         oh = container_of0(handle, struct osd_thandle, ot_super);
2464         LASSERT(oh->ot_handle == NULL);
2465
2466         OSD_DECLARE_OP(oh, xattr_set);
2467         if (strcmp(name, XATTR_NAME_VERSION) == 0)
2468                 oh->ot_credits += osd_dto_credits_noquota[DTO_ATTR_SET_BASE];
2469         else
2470                 oh->ot_credits += osd_dto_credits_noquota[DTO_XATTR_SET];
2471
2472         return 0;
2473 }
2474
2475 /*
2476  * Set the 64-bit version for object
2477  */
2478 static void osd_object_version_set(const struct lu_env *env,
2479                                    struct dt_object *dt,
2480                                    dt_obj_version_t *new_version)
2481 {
2482         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2483
2484         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
2485                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2486
2487         LDISKFS_I(inode)->i_fs_version = *new_version;
2488         /** Version is set after all inode operations are finished,
2489          *  so we should mark it dirty here */
2490         inode->i_sb->s_op->dirty_inode(inode);
2491 }
2492
2493 /*
2494  * Concurrency: @dt is write locked.
2495  */
2496 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
2497                          const struct lu_buf *buf, const char *name, int fl,
2498                          struct thandle *handle, struct lustre_capa *capa)
2499 {
2500         LASSERT(handle != NULL);
2501
2502         /* version set is not real XATTR */
2503         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2504                 /* for version we are just using xattr API but change inode
2505                  * field instead */
2506                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2507                 osd_object_version_set(env, dt, buf->lb_buf);
2508                 return sizeof(dt_obj_version_t);
2509         }
2510
2511         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2512                 return -EACCES;
2513
2514         OSD_EXEC_OP(handle, xattr_set);
2515         return __osd_xattr_set(env, dt, buf, name, fl);
2516 }
2517
2518 /*
2519  * Concurrency: @dt is read locked.
2520  */
2521 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
2522                           struct lu_buf *buf, struct lustre_capa *capa)
2523 {
2524         struct osd_object      *obj    = osd_dt_obj(dt);
2525         struct inode           *inode  = obj->oo_inode;
2526         struct osd_thread_info *info   = osd_oti_get(env);
2527         struct dentry          *dentry = &info->oti_obj_dentry;
2528
2529         LASSERT(dt_object_exists(dt));
2530         LASSERT(inode->i_op != NULL && inode->i_op->listxattr != NULL);
2531         LASSERT(osd_read_locked(env, obj) || osd_write_locked(env, obj));
2532
2533         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2534                 return -EACCES;
2535
2536         dentry->d_inode = inode;
2537         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
2538 }
2539
2540 static int osd_declare_xattr_del(const struct lu_env *env,
2541                                  struct dt_object *dt, const char *name,
2542                                  struct thandle *handle)
2543 {
2544         struct osd_thandle *oh;
2545
2546         LASSERT(dt_object_exists(dt));
2547         LASSERT(handle != NULL);
2548
2549         oh = container_of0(handle, struct osd_thandle, ot_super);
2550         LASSERT(oh->ot_handle == NULL);
2551
2552         OSD_DECLARE_OP(oh, xattr_set);
2553         oh->ot_credits += osd_dto_credits_noquota[DTO_XATTR_SET];
2554
2555         return 0;
2556 }
2557
2558 /*
2559  * Concurrency: @dt is write locked.
2560  */
2561 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
2562                          const char *name, struct thandle *handle,
2563                          struct lustre_capa *capa)
2564 {
2565         struct osd_object      *obj    = osd_dt_obj(dt);
2566         struct inode           *inode  = obj->oo_inode;
2567         struct osd_thread_info *info   = osd_oti_get(env);
2568         struct dentry          *dentry = &info->oti_obj_dentry;
2569         int                     rc;
2570
2571         LASSERT(dt_object_exists(dt));
2572         LASSERT(inode->i_op != NULL && inode->i_op->removexattr != NULL);
2573         LASSERT(osd_write_locked(env, obj));
2574         LASSERT(handle != NULL);
2575
2576         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2577                 return -EACCES;
2578
2579         OSD_EXEC_OP(handle, xattr_set);
2580
2581         dentry->d_inode = inode;
2582         rc = inode->i_op->removexattr(dentry, name);
2583         return rc;
2584 }
2585
2586 static struct obd_capa *osd_capa_get(const struct lu_env *env,
2587                                      struct dt_object *dt,
2588                                      struct lustre_capa *old,
2589                                      __u64 opc)
2590 {
2591         struct osd_thread_info *info = osd_oti_get(env);
2592         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
2593         struct osd_object *obj = osd_dt_obj(dt);
2594         struct osd_device *dev = osd_obj2dev(obj);
2595         struct lustre_capa_key *key = &info->oti_capa_key;
2596         struct lustre_capa *capa = &info->oti_capa;
2597         struct obd_capa *oc;
2598         struct md_capainfo *ci;
2599         int rc;
2600         ENTRY;
2601
2602         if (!dev->od_fl_capa)
2603                 RETURN(ERR_PTR(-ENOENT));
2604
2605         LASSERT(dt_object_exists(dt));
2606         LINVRNT(osd_invariant(obj));
2607
2608         /* renewal sanity check */
2609         if (old && osd_object_auth(env, dt, old, opc))
2610                 RETURN(ERR_PTR(-EACCES));
2611
2612         ci = md_capainfo(env);
2613         if (unlikely(!ci))
2614                 RETURN(ERR_PTR(-ENOENT));
2615
2616         switch (ci->mc_auth) {
2617         case LC_ID_NONE:
2618                 RETURN(NULL);
2619         case LC_ID_PLAIN:
2620                 capa->lc_uid = obj->oo_inode->i_uid;
2621                 capa->lc_gid = obj->oo_inode->i_gid;
2622                 capa->lc_flags = LC_ID_PLAIN;
2623                 break;
2624         case LC_ID_CONVERT: {
2625                 __u32 d[4], s[4];
2626
2627                 s[0] = obj->oo_inode->i_uid;
2628                 cfs_get_random_bytes(&(s[1]), sizeof(__u32));
2629                 s[2] = obj->oo_inode->i_gid;
2630                 cfs_get_random_bytes(&(s[3]), sizeof(__u32));
2631                 rc = capa_encrypt_id(d, s, key->lk_key, CAPA_HMAC_KEY_MAX_LEN);
2632                 if (unlikely(rc))
2633                         RETURN(ERR_PTR(rc));
2634
2635                 capa->lc_uid   = ((__u64)d[1] << 32) | d[0];
2636                 capa->lc_gid   = ((__u64)d[3] << 32) | d[2];
2637                 capa->lc_flags = LC_ID_CONVERT;
2638                 break;
2639         }
2640         default:
2641                 RETURN(ERR_PTR(-EINVAL));
2642         }
2643
2644         capa->lc_fid = *fid;
2645         capa->lc_opc = opc;
2646         capa->lc_flags |= dev->od_capa_alg << 24;
2647         capa->lc_timeout = dev->od_capa_timeout;
2648         capa->lc_expiry = 0;
2649
2650         oc = capa_lookup(dev->od_capa_hash, capa, 1);
2651         if (oc) {
2652                 LASSERT(!capa_is_expired(oc));
2653                 RETURN(oc);
2654         }
2655
2656         cfs_spin_lock(&capa_lock);
2657         *key = dev->od_capa_keys[1];
2658         cfs_spin_unlock(&capa_lock);
2659
2660         capa->lc_keyid = key->lk_keyid;
2661         capa->lc_expiry = cfs_time_current_sec() + dev->od_capa_timeout;
2662
2663         rc = capa_hmac(capa->lc_hmac, capa, key->lk_key);
2664         if (rc) {
2665                 DEBUG_CAPA(D_ERROR, capa, "HMAC failed: %d for", rc);
2666                 RETURN(ERR_PTR(rc));
2667         }
2668
2669         oc = capa_add(dev->od_capa_hash, capa);
2670         RETURN(oc);
2671 }
2672
2673 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt)
2674 {
2675         struct osd_object       *obj    = osd_dt_obj(dt);
2676         struct inode            *inode  = obj->oo_inode;
2677         struct osd_thread_info  *info   = osd_oti_get(env);
2678         struct dentry           *dentry = &info->oti_obj_dentry;
2679         struct file             *file   = &info->oti_file;
2680         int                     rc;
2681
2682         ENTRY;
2683
2684         dentry->d_inode = inode;
2685         file->f_dentry = dentry;
2686         file->f_mapping = inode->i_mapping;
2687         file->f_op = inode->i_fop;
2688         mutex_lock(&inode->i_mutex);
2689         rc = file->f_op->fsync(file, dentry, 0);
2690         mutex_unlock(&inode->i_mutex);
2691         RETURN(rc);
2692 }
2693
2694 static int osd_data_get(const struct lu_env *env, struct dt_object *dt,
2695                         void **data)
2696 {
2697         struct osd_object *obj = osd_dt_obj(dt);
2698         ENTRY;
2699
2700         *data = (void *)obj->oo_inode;
2701         RETURN(0);
2702 }
2703
2704 /*
2705  * Index operations.
2706  */
2707
2708 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
2709                            const struct dt_index_features *feat)
2710 {
2711         struct iam_descr *descr;
2712
2713         if (osd_object_is_root(o))
2714                 return feat == &dt_directory_features;
2715
2716         LASSERT(o->oo_dir != NULL);
2717
2718         descr = o->oo_dir->od_container.ic_descr;
2719         if (feat == &dt_directory_features) {
2720                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
2721                         return 1;
2722                 else
2723                         return 0;
2724         } else {
2725                 return
2726                         feat->dif_keysize_min <= descr->id_key_size &&
2727                         descr->id_key_size <= feat->dif_keysize_max &&
2728                         feat->dif_recsize_min <= descr->id_rec_size &&
2729                         descr->id_rec_size <= feat->dif_recsize_max &&
2730                         !(feat->dif_flags & (DT_IND_VARKEY |
2731                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
2732                         ergo(feat->dif_flags & DT_IND_UPDATE,
2733                              1 /* XXX check that object (and file system) is
2734                                 * writable */);
2735         }
2736 }
2737
2738 static int osd_iam_container_init(const struct lu_env *env,
2739                                   struct osd_object *obj,
2740                                   struct osd_directory *dir)
2741 {
2742         struct iam_container *bag = &dir->od_container;
2743         int result;
2744
2745         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
2746         if (result != 0)
2747                 return result;
2748
2749         result = iam_container_setup(bag);
2750         if (result == 0)
2751                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
2752         else
2753                 iam_container_fini(bag);
2754
2755         return result;
2756 }
2757
2758
2759 /*
2760  * Concurrency: no external locking is necessary.
2761  */
2762 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
2763                          const struct dt_index_features *feat)
2764 {
2765         int                      result;
2766         int                      skip_iam = 0;
2767         struct osd_object       *obj = osd_dt_obj(dt);
2768         struct osd_device       *osd = osd_obj2dev(obj);
2769
2770         LINVRNT(osd_invariant(obj));
2771         LASSERT(dt_object_exists(dt));
2772
2773         if (osd_object_is_root(obj)) {
2774                 dt->do_index_ops = &osd_index_ea_ops;
2775                 result = 0;
2776         } else if (feat == &dt_directory_features && osd->od_iop_mode) {
2777                 dt->do_index_ops = &osd_index_ea_ops;
2778                 if (S_ISDIR(obj->oo_inode->i_mode))
2779                         result = 0;
2780                 else
2781                         result = -ENOTDIR;
2782                 skip_iam = 1;
2783         } else if (unlikely(feat == &dt_otable_features)) {
2784                 dt->do_index_ops = &osd_otable_ops;
2785                 return 0;
2786         } else if (feat == &dt_acct_features) {
2787                 dt->do_index_ops = &osd_acct_index_ops;
2788                 result = 0;
2789                 skip_iam = 1;
2790         } else if (!osd_has_index(obj)) {
2791                 struct osd_directory *dir;
2792
2793                 OBD_ALLOC_PTR(dir);
2794                 if (dir != NULL) {
2795
2796                         cfs_spin_lock(&obj->oo_guard);
2797                         if (obj->oo_dir == NULL)
2798                                 obj->oo_dir = dir;
2799                         else
2800                                 /*
2801                                  * Concurrent thread allocated container data.
2802                                  */
2803                                 OBD_FREE_PTR(dir);
2804                         cfs_spin_unlock(&obj->oo_guard);
2805                         /*
2806                          * Now, that we have container data, serialize its
2807                          * initialization.
2808                          */
2809                         cfs_down_write(&obj->oo_ext_idx_sem);
2810                         /*
2811                          * recheck under lock.
2812                          */
2813                         if (!osd_has_index(obj))
2814                                 result = osd_iam_container_init(env, obj, dir);
2815                         else
2816                                 result = 0;
2817                         cfs_up_write(&obj->oo_ext_idx_sem);
2818                 } else {
2819                         result = -ENOMEM;
2820                 }
2821         } else {
2822                 result = 0;
2823         }
2824
2825         if (result == 0 && skip_iam == 0) {
2826                 if (!osd_iam_index_probe(env, obj, feat))
2827                         result = -ENOTDIR;
2828         }
2829         LINVRNT(osd_invariant(obj));
2830
2831         return result;
2832 }
2833
2834 static int osd_otable_it_attr_get(const struct lu_env *env,
2835                                  struct dt_object *dt,
2836                                  struct lu_attr *attr,
2837                                  struct lustre_capa *capa)
2838 {
2839         attr->la_valid = 0;
2840         return 0;
2841 }
2842
2843 static const struct dt_object_operations osd_obj_ops = {
2844         .do_read_lock         = osd_object_read_lock,
2845         .do_write_lock        = osd_object_write_lock,
2846         .do_read_unlock       = osd_object_read_unlock,
2847         .do_write_unlock      = osd_object_write_unlock,
2848         .do_write_locked      = osd_object_write_locked,
2849         .do_attr_get          = osd_attr_get,
2850         .do_declare_attr_set  = osd_declare_attr_set,
2851         .do_attr_set          = osd_attr_set,
2852         .do_ah_init           = osd_ah_init,
2853         .do_declare_create    = osd_declare_object_create,
2854         .do_create            = osd_object_create,
2855         .do_declare_destroy   = osd_declare_object_destroy,
2856         .do_destroy           = osd_object_destroy,
2857         .do_index_try         = osd_index_try,
2858         .do_declare_ref_add   = osd_declare_object_ref_add,
2859         .do_ref_add           = osd_object_ref_add,
2860         .do_declare_ref_del   = osd_declare_object_ref_del,
2861         .do_ref_del           = osd_object_ref_del,
2862         .do_xattr_get         = osd_xattr_get,
2863         .do_declare_xattr_set = osd_declare_xattr_set,
2864         .do_xattr_set         = osd_xattr_set,
2865         .do_declare_xattr_del = osd_declare_xattr_del,
2866         .do_xattr_del         = osd_xattr_del,
2867         .do_xattr_list        = osd_xattr_list,
2868         .do_capa_get          = osd_capa_get,
2869         .do_object_sync       = osd_object_sync,
2870         .do_data_get          = osd_data_get,
2871 };
2872
2873 /**
2874  * dt_object_operations for interoperability mode
2875  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
2876  */
2877 static const struct dt_object_operations osd_obj_ea_ops = {
2878         .do_read_lock         = osd_object_read_lock,
2879         .do_write_lock        = osd_object_write_lock,
2880         .do_read_unlock       = osd_object_read_unlock,
2881         .do_write_unlock      = osd_object_write_unlock,
2882         .do_write_locked      = osd_object_write_locked,
2883         .do_attr_get          = osd_attr_get,
2884         .do_declare_attr_set  = osd_declare_attr_set,
2885         .do_attr_set          = osd_attr_set,
2886         .do_ah_init           = osd_ah_init,
2887         .do_declare_create    = osd_declare_object_create,
2888         .do_create            = osd_object_ea_create,
2889         .do_declare_destroy   = osd_declare_object_destroy,
2890         .do_destroy           = osd_object_destroy,
2891         .do_index_try         = osd_index_try,
2892         .do_declare_ref_add   = osd_declare_object_ref_add,
2893         .do_ref_add           = osd_object_ref_add,
2894         .do_declare_ref_del   = osd_declare_object_ref_del,
2895         .do_ref_del           = osd_object_ref_del,
2896         .do_xattr_get         = osd_xattr_get,
2897         .do_declare_xattr_set = osd_declare_xattr_set,
2898         .do_xattr_set         = osd_xattr_set,
2899         .do_declare_xattr_del = osd_declare_xattr_del,
2900         .do_xattr_del         = osd_xattr_del,
2901         .do_xattr_list        = osd_xattr_list,
2902         .do_capa_get          = osd_capa_get,
2903         .do_object_sync       = osd_object_sync,
2904         .do_data_get          = osd_data_get,
2905 };
2906
2907 static const struct dt_object_operations osd_obj_otable_it_ops = {
2908         .do_attr_get    = osd_otable_it_attr_get,
2909         .do_index_try   = osd_index_try,
2910 };
2911
2912 static int osd_index_declare_iam_delete(const struct lu_env *env,
2913                                         struct dt_object *dt,
2914                                         const struct dt_key *key,
2915                                         struct thandle *handle)
2916 {
2917         struct osd_thandle    *oh;
2918
2919         oh = container_of0(handle, struct osd_thandle, ot_super);
2920         LASSERT(oh->ot_handle == NULL);
2921
2922         OSD_DECLARE_OP(oh, delete);
2923         oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
2924
2925         return 0;
2926 }
2927
2928 /**
2929  *      delete a (key, value) pair from index \a dt specified by \a key
2930  *
2931  *      \param  dt      osd index object
2932  *      \param  key     key for index
2933  *      \param  rec     record reference
2934  *      \param  handle  transaction handler
2935  *
2936  *      \retval  0  success
2937  *      \retval -ve   failure
2938  */
2939
2940 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
2941                                 const struct dt_key *key,
2942                                 struct thandle *handle,
2943                                 struct lustre_capa *capa)
2944 {
2945         struct osd_thread_info *oti = osd_oti_get(env);
2946         struct osd_object      *obj = osd_dt_obj(dt);
2947         struct osd_thandle     *oh;
2948         struct iam_path_descr  *ipd;
2949         struct iam_container   *bag = &obj->oo_dir->od_container;
2950         int                     rc;
2951
2952         ENTRY;
2953
2954         LINVRNT(osd_invariant(obj));
2955         LASSERT(dt_object_exists(dt));
2956         LASSERT(bag->ic_object == obj->oo_inode);
2957         LASSERT(handle != NULL);
2958
2959         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
2960                 RETURN(-EACCES);
2961
2962         OSD_EXEC_OP(handle, delete);
2963
2964         ipd = osd_idx_ipd_get(env, bag);
2965         if (unlikely(ipd == NULL))
2966                 RETURN(-ENOMEM);
2967
2968         oh = container_of0(handle, struct osd_thandle, ot_super);
2969         LASSERT(oh->ot_handle != NULL);
2970         LASSERT(oh->ot_handle->h_transaction != NULL);
2971
2972         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
2973                 /* swab quota uid/gid provided by caller */
2974                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
2975                 key = (const struct dt_key *)&oti->oti_quota_id;
2976         }
2977
2978         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
2979         osd_ipd_put(env, bag, ipd);
2980         LINVRNT(osd_invariant(obj));
2981         RETURN(rc);
2982 }
2983
2984 static int osd_index_declare_ea_delete(const struct lu_env *env,
2985                                        struct dt_object *dt,
2986                                        const struct dt_key *key,
2987                                        struct thandle *handle)
2988 {
2989         struct osd_thandle *oh;
2990         struct inode       *inode;
2991         int                 rc;
2992         ENTRY;
2993
2994         LASSERT(dt_object_exists(dt));
2995         LASSERT(handle != NULL);
2996
2997         oh = container_of0(handle, struct osd_thandle, ot_super);
2998         LASSERT(oh->ot_handle == NULL);
2999
3000         OSD_DECLARE_OP(oh, delete);
3001         oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
3002
3003         inode = osd_dt_obj(dt)->oo_inode;
3004         LASSERT(inode);
3005
3006         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
3007                                    true, true, NULL, false);
3008         RETURN(rc);
3009 }
3010
3011 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3012                                           struct dt_rec *fid)
3013 {
3014         struct osd_fid_pack *rec;
3015         int                  rc = -ENODATA;
3016
3017         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3018                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3019                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3020         }
3021         RETURN(rc);
3022 }
3023
3024 /**
3025  * Index delete function for interoperability mode (b11826).
3026  * It will remove the directory entry added by osd_index_ea_insert().
3027  * This entry is needed to maintain name->fid mapping.
3028  *
3029  * \param key,  key i.e. file entry to be deleted
3030  *
3031  * \retval   0, on success
3032  * \retval -ve, on error
3033  */
3034 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3035                                const struct dt_key *key,
3036                                struct thandle *handle,
3037                                struct lustre_capa *capa)
3038 {
3039         struct osd_object          *obj    = osd_dt_obj(dt);
3040         struct inode               *dir    = obj->oo_inode;
3041         struct dentry              *dentry;
3042         struct osd_thandle         *oh;
3043         struct ldiskfs_dir_entry_2 *de;
3044         struct buffer_head         *bh;
3045         struct htree_lock          *hlock = NULL;
3046         int                         rc;
3047
3048         ENTRY;
3049
3050         LINVRNT(osd_invariant(obj));
3051         LASSERT(dt_object_exists(dt));
3052         LASSERT(handle != NULL);
3053
3054         OSD_EXEC_OP(handle, delete);
3055
3056         oh = container_of(handle, struct osd_thandle, ot_super);
3057         LASSERT(oh->ot_handle != NULL);
3058         LASSERT(oh->ot_handle->h_transaction != NULL);
3059
3060         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3061                 RETURN(-EACCES);
3062
3063         dentry = osd_child_dentry_get(env, obj,
3064                                       (char *)key, strlen((char *)key));
3065
3066         if (obj->oo_hl_head != NULL) {
3067                 hlock = osd_oti_get(env)->oti_hlock;
3068                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3069                                    dir, LDISKFS_HLOCK_DEL);
3070         } else {
3071                 cfs_down_write(&obj->oo_ext_idx_sem);
3072         }
3073
3074         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
3075         if (bh) {
3076                 rc = ldiskfs_delete_entry(oh->ot_handle,
3077                                           dir, de, bh);
3078                 brelse(bh);
3079         } else {
3080                 rc = -ENOENT;
3081         }
3082         if (hlock != NULL)
3083                 ldiskfs_htree_unlock(hlock);
3084         else
3085                 cfs_up_write(&obj->oo_ext_idx_sem);
3086
3087         LASSERT(osd_invariant(obj));
3088         RETURN(rc);
3089 }
3090
3091 /**
3092  *      Lookup index for \a key and copy record to \a rec.
3093  *
3094  *      \param  dt      osd index object
3095  *      \param  key     key for index
3096  *      \param  rec     record reference
3097  *
3098  *      \retval  +ve  success : exact mach
3099  *      \retval  0    return record with key not greater than \a key
3100  *      \retval -ve   failure
3101  */
3102 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
3103                                 struct dt_rec *rec, const struct dt_key *key,
3104                                 struct lustre_capa *capa)
3105 {
3106         struct osd_object      *obj = osd_dt_obj(dt);
3107         struct iam_path_descr  *ipd;
3108         struct iam_container   *bag = &obj->oo_dir->od_container;
3109         struct osd_thread_info *oti = osd_oti_get(env);
3110         struct iam_iterator    *it = &oti->oti_idx_it;
3111         struct iam_rec         *iam_rec;
3112         int                     rc;
3113
3114         ENTRY;
3115
3116         LASSERT(osd_invariant(obj));
3117         LASSERT(dt_object_exists(dt));
3118         LASSERT(bag->ic_object == obj->oo_inode);
3119
3120         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
3121                 RETURN(-EACCES);
3122
3123         ipd = osd_idx_ipd_get(env, bag);
3124         if (IS_ERR(ipd))
3125                 RETURN(-ENOMEM);
3126
3127         /* got ipd now we can start iterator. */
3128         iam_it_init(it, bag, 0, ipd);
3129
3130         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3131                 /* swab quota uid/gid provided by caller */
3132                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3133                 key = (const struct dt_key *)&oti->oti_quota_id;
3134         }
3135
3136         rc = iam_it_get(it, (struct iam_key *)key);
3137         if (rc >= 0) {
3138                 if (S_ISDIR(obj->oo_inode->i_mode))
3139                         iam_rec = (struct iam_rec *)oti->oti_ldp;
3140                 else
3141                         iam_rec = (struct iam_rec *) rec;
3142
3143                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
3144
3145                 if (S_ISDIR(obj->oo_inode->i_mode))
3146                         osd_fid_unpack((struct lu_fid *) rec,
3147                                        (struct osd_fid_pack *)iam_rec);
3148                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
3149                         osd_quota_unpack(obj, rec);
3150         }
3151
3152         iam_it_put(it);
3153         iam_it_fini(it);
3154         osd_ipd_put(env, bag, ipd);
3155
3156         LINVRNT(osd_invariant(obj));
3157
3158         RETURN(rc);
3159 }
3160
3161 static int osd_index_declare_iam_insert(const struct lu_env *env,
3162                                         struct dt_object *dt,
3163                                         const struct dt_rec *rec,
3164                                         const struct dt_key *key,
3165                                         struct thandle *handle)
3166 {
3167         struct osd_thandle *oh;
3168
3169         LASSERT(dt_object_exists(dt));
3170         LASSERT(handle != NULL);
3171
3172         oh = container_of0(handle, struct osd_thandle, ot_super);
3173         LASSERT(oh->ot_handle == NULL);
3174
3175         OSD_DECLARE_OP(oh, insert);
3176         oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
3177
3178         return 0;
3179 }
3180
3181 /**
3182  *      Inserts (key, value) pair in \a dt index object.
3183  *
3184  *      \param  dt      osd index object
3185  *      \param  key     key for index
3186  *      \param  rec     record reference
3187  *      \param  th      transaction handler
3188  *
3189  *      \retval  0  success
3190  *      \retval -ve failure
3191  */
3192 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
3193                                 const struct dt_rec *rec,
3194                                 const struct dt_key *key, struct thandle *th,
3195                                 struct lustre_capa *capa, int ignore_quota)
3196 {
3197         struct osd_object     *obj = osd_dt_obj(dt);
3198         struct iam_path_descr *ipd;
3199         struct osd_thandle    *oh;
3200         struct iam_container  *bag = &obj->oo_dir->od_container;
3201 #ifdef HAVE_QUOTA_SUPPORT
3202         cfs_cap_t              save = cfs_curproc_cap_pack();
3203 #endif
3204         struct osd_thread_info *oti = osd_oti_get(env);
3205         struct iam_rec         *iam_rec;
3206         int                     rc;
3207
3208         ENTRY;
3209
3210         LINVRNT(osd_invariant(obj));
3211         LASSERT(dt_object_exists(dt));
3212         LASSERT(bag->ic_object == obj->oo_inode);
3213         LASSERT(th != NULL);
3214
3215         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3216                 RETURN(-EACCES);
3217
3218         OSD_EXEC_OP(th, insert);
3219
3220         ipd = osd_idx_ipd_get(env, bag);
3221         if (unlikely(ipd == NULL))
3222                 RETURN(-ENOMEM);
3223
3224         oh = container_of0(th, struct osd_thandle, ot_super);
3225         LASSERT(oh->ot_handle != NULL);
3226         LASSERT(oh->ot_handle->h_transaction != NULL);
3227 #ifdef HAVE_QUOTA_SUPPORT
3228         if (ignore_quota)
3229                 cfs_cap_raise(CFS_CAP_SYS_RESOURCE);
3230         else
3231                 cfs_cap_lower(CFS_CAP_SYS_RESOURCE);
3232 #endif
3233         if (S_ISDIR(obj->oo_inode->i_mode)) {
3234                 iam_rec = (struct iam_rec *)oti->oti_ldp;
3235                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
3236         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3237                 /* pack quota uid/gid */
3238                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3239                 key = (const struct dt_key *)&oti->oti_quota_id;
3240                 /* pack quota record */
3241                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
3242                 iam_rec = (struct iam_rec *)rec;
3243         } else {
3244                 iam_rec = (struct iam_rec *)rec;
3245         }
3246
3247         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
3248                         iam_rec, ipd);
3249 #ifdef HAVE_QUOTA_SUPPORT
3250         cfs_curproc_cap_unpack(save);
3251 #endif
3252         osd_ipd_put(env, bag, ipd);
3253         LINVRNT(osd_invariant(obj));
3254         RETURN(rc);
3255 }
3256
3257 /**
3258  * Calls ldiskfs_add_entry() to add directory entry
3259  * into the directory. This is required for
3260  * interoperability mode (b11826)
3261  *
3262  * \retval   0, on success
3263  * \retval -ve, on error
3264  */
3265 static int __osd_ea_add_rec(struct osd_thread_info *info,
3266                             struct osd_object *pobj, struct inode  *cinode,
3267                             const char *name, const struct dt_rec *fid,
3268                             struct htree_lock *hlock, struct thandle *th)
3269 {
3270         struct ldiskfs_dentry_param *ldp;
3271         struct dentry               *child;
3272         struct osd_thandle          *oth;
3273         int                          rc;
3274
3275         oth = container_of(th, struct osd_thandle, ot_super);
3276         LASSERT(oth->ot_handle != NULL);
3277         LASSERT(oth->ot_handle->h_transaction != NULL);
3278
3279         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
3280
3281         /* XXX: remove fid_is_igif() check here.
3282          * IGIF check is just to handle insertion of .. when it is 'ROOT',
3283          * it is IGIF now but needs FID in dir entry as well for readdir
3284          * to work.
3285          * LU-838 should fix that and remove fid_is_igif() check */
3286         if (fid_is_igif((struct lu_fid *)fid) ||
3287             fid_is_norm((struct lu_fid *)fid)) {
3288                 ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3289                 osd_get_ldiskfs_dirent_param(ldp, fid);
3290                 child->d_fsdata = (void *)ldp;
3291         } else {
3292                 child->d_fsdata = NULL;
3293         }
3294         rc = osd_ldiskfs_add_entry(oth->ot_handle, child, cinode, hlock);
3295
3296         RETURN(rc);
3297 }
3298
3299 /**
3300  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
3301  * into the directory.Also sets flags into osd object to
3302  * indicate dot and dotdot are created. This is required for
3303  * interoperability mode (b11826)
3304  *
3305  * \param dir   directory for dot and dotdot fixup.
3306  * \param obj   child object for linking
3307  *
3308  * \retval   0, on success
3309  * \retval -ve, on error
3310  */
3311 static int osd_add_dot_dotdot(struct osd_thread_info *info,
3312                               struct osd_object *dir,
3313                               struct inode  *parent_dir, const char *name,
3314                               const struct dt_rec *dot_fid,
3315                               const struct dt_rec *dot_dot_fid,
3316                               struct thandle *th)
3317 {
3318         struct inode                *inode = dir->oo_inode;
3319         struct ldiskfs_dentry_param *dot_ldp;
3320         struct ldiskfs_dentry_param *dot_dot_ldp;
3321         struct osd_thandle          *oth;
3322         int result = 0;
3323
3324         oth = container_of(th, struct osd_thandle, ot_super);
3325         LASSERT(oth->ot_handle->h_transaction != NULL);
3326         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
3327
3328         if (strcmp(name, dot) == 0) {
3329                 if (dir->oo_compat_dot_created) {
3330                         result = -EEXIST;
3331                 } else {
3332                         LASSERT(inode == parent_dir);
3333                         dir->oo_compat_dot_created = 1;
3334                         result = 0;
3335                 }
3336         } else if(strcmp(name, dotdot) == 0) {
3337                 dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3338                 dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
3339
3340                 if (!dir->oo_compat_dot_created)
3341                         return -EINVAL;
3342                 if (!fid_is_igif((struct lu_fid *)dot_fid)) {
3343                         osd_get_ldiskfs_dirent_param(dot_ldp, dot_fid);
3344                         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
3345                 } else {
3346                         dot_ldp = NULL;
3347                         dot_dot_ldp = NULL;
3348                 }
3349                 /* in case of rename, dotdot is already created */
3350                 if (dir->oo_compat_dotdot_created) {
3351                         return __osd_ea_add_rec(info, dir, parent_dir, name,
3352                                                 dot_dot_fid, NULL, th);
3353                 }
3354
3355                 result = ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
3356                                                 inode, dot_ldp, dot_dot_ldp);
3357                 if (result == 0)
3358                        dir->oo_compat_dotdot_created = 1;
3359         }
3360
3361         return result;
3362 }
3363
3364
3365 /**
3366  * It will call the appropriate osd_add* function and return the
3367  * value, return by respective functions.
3368  */
3369 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
3370                           struct inode *cinode, const char *name,
3371                           const struct dt_rec *fid, struct thandle *th)
3372 {
3373         struct osd_thread_info *info   = osd_oti_get(env);
3374         struct htree_lock      *hlock;
3375         int                     rc;
3376
3377         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
3378
3379         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
3380                                                    name[2] =='\0'))) {
3381                 if (hlock != NULL) {
3382                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3383                                            pobj->oo_inode, 0);
3384                 } else {
3385                         cfs_down_write(&pobj->oo_ext_idx_sem);
3386                 }
3387                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
3388                      (struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
3389                                         fid, th);
3390         } else {
3391                 if (hlock != NULL) {
3392                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3393                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
3394                 } else {
3395                         cfs_down_write(&pobj->oo_ext_idx_sem);
3396                 }
3397
3398                 rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
3399                                       hlock, th);
3400         }
3401         if (hlock != NULL)
3402                 ldiskfs_htree_unlock(hlock);
3403         else
3404                 cfs_up_write(&pobj->oo_ext_idx_sem);
3405
3406         return rc;
3407 }
3408
3409 static int
3410 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
3411                       struct osd_idmap_cache *oic)
3412 {
3413         struct osd_scrub    *scrub = &dev->od_scrub;
3414         struct lu_fid       *fid   = &oic->oic_fid;
3415         struct osd_inode_id *id    = &oti->oti_id;
3416         int                  once  = 0;
3417         int                  rc;
3418         ENTRY;
3419
3420 again:
3421         rc = osd_oi_lookup(oti, dev, fid, id);
3422         if (rc != 0 && rc != -ENOENT)
3423                 RETURN(rc);
3424
3425         if (rc == 0 && osd_id_eq(id, &oic->oic_lid))
3426                 RETURN(0);
3427
3428         if (thread_is_running(&scrub->os_thread)) {
3429                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
3430                 /* There is race condition between osd_oi_lookup and OI scrub.
3431                  * The OI scrub finished just after osd_oi_lookup() failure.
3432                  * Under such case, it is unnecessary to trigger OI scrub again,
3433                  * but try to call osd_oi_lookup() again. */
3434                 if (unlikely(rc == -EAGAIN))
3435                         goto again;
3436
3437                 RETURN(rc);
3438         }
3439
3440         if (!scrub->os_no_scrub && ++once == 1) {
3441                 CDEBUG(D_LFSCK, "Trigger OI scrub by RPC for "DFID"\n",
3442                        PFID(fid));
3443                 rc = osd_scrub_start(dev);
3444                 LCONSOLE_ERROR("%.16s: trigger OI scrub by RPC for "DFID
3445                                ", rc = %d [2]\n",
3446                                LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
3447                                PFID(fid), rc);
3448                 if (rc == 0)
3449                         goto again;
3450         }
3451
3452         RETURN(rc = -EREMCHG);
3453 }
3454
3455 /**
3456  * Calls ->lookup() to find dentry. From dentry get inode and
3457  * read inode's ea to get fid. This is required for  interoperability
3458  * mode (b11826)
3459  *
3460  * \retval   0, on success
3461  * \retval -ve, on error
3462  */
3463 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
3464                              struct dt_rec *rec, const struct dt_key *key)
3465 {
3466         struct inode               *dir    = obj->oo_inode;
3467         struct dentry              *dentry;
3468         struct ldiskfs_dir_entry_2 *de;
3469         struct buffer_head         *bh;
3470         struct lu_fid              *fid = (struct lu_fid *) rec;
3471         struct htree_lock          *hlock = NULL;
3472         int                         ino;
3473         int                         rc;
3474
3475         LASSERT(dir->i_op != NULL && dir->i_op->lookup != NULL);
3476
3477         dentry = osd_child_dentry_get(env, obj,
3478                                       (char *)key, strlen((char *)key));
3479
3480         if (obj->oo_hl_head != NULL) {
3481                 hlock = osd_oti_get(env)->oti_hlock;
3482                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3483                                    dir, LDISKFS_HLOCK_LOOKUP);
3484         } else {
3485                 cfs_down_read(&obj->oo_ext_idx_sem);
3486         }
3487
3488         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
3489         if (bh) {
3490                 struct osd_thread_info *oti = osd_oti_get(env);
3491                 struct osd_idmap_cache *oic = &oti->oti_cache;
3492                 struct osd_device *dev = osd_obj2dev(obj);
3493                 struct osd_scrub *scrub = &dev->od_scrub;
3494                 struct scrub_file *sf = &scrub->os_file;
3495
3496                 ino = le32_to_cpu(de->inode);
3497                 rc = osd_get_fid_from_dentry(de, rec);
3498
3499                 /* done with de, release bh */
3500                 brelse(bh);
3501                 if (rc != 0)
3502                         rc = osd_ea_fid_get(env, obj, ino, fid, &oic->oic_lid);
3503                 else
3504                         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
3505                 if (rc != 0 || !fid_is_norm(fid)) {
3506                         fid_zero(&oic->oic_fid);
3507                         GOTO(out, rc);
3508                 }
3509
3510                 oic->oic_fid = *fid;
3511                 if ((scrub->os_pos_current <= ino) &&
3512                     (sf->sf_flags & SF_INCONSISTENT ||
3513                      ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
3514                                       sf->sf_oi_bitmap)))
3515                         rc = osd_consistency_check(oti, dev, oic);
3516         } else {
3517                 rc = -ENOENT;
3518         }
3519
3520         GOTO(out, rc);
3521
3522 out:
3523         if (hlock != NULL)
3524                 ldiskfs_htree_unlock(hlock);
3525         else
3526                 cfs_up_read(&obj->oo_ext_idx_sem);
3527         return rc;
3528 }
3529
3530 /**
3531  * Find the osd object for given fid.
3532  *
3533  * \param fid need to find the osd object having this fid
3534  *
3535  * \retval osd_object on success
3536  * \retval        -ve on error
3537  */
3538 struct osd_object *osd_object_find(const struct lu_env *env,
3539                                    struct dt_object *dt,
3540                                    const struct lu_fid *fid)
3541 {
3542         struct lu_device  *ludev = dt->do_lu.lo_dev;
3543         struct osd_object *child = NULL;
3544         struct lu_object  *luch;
3545         struct lu_object  *lo;
3546
3547         /*
3548          * at this point topdev might not exist yet
3549          * (i.e. MGS is preparing profiles). so we can
3550          * not rely on topdev and instead lookup with
3551          * our device passed as topdev. this can't work
3552          * if the object isn't cached yet (as osd doesn't
3553          * allocate lu_header). IOW, the object must be
3554          * in the cache, otherwise lu_object_alloc() crashes
3555          * -bzzz
3556          */
3557         luch = lu_object_find_at(env, ludev, fid, NULL);
3558         if (!IS_ERR(luch)) {
3559                 if (lu_object_exists(luch)) {
3560                         lo = lu_object_locate(luch->lo_header, ludev->ld_type);
3561                         if (lo != NULL)
3562                                 child = osd_obj(lo);
3563                         else
3564                                 LU_OBJECT_DEBUG(D_ERROR, env, luch,
3565                                                 "lu_object can't be located"
3566                                                 DFID"\n", PFID(fid));
3567
3568                         if (child == NULL) {
3569                                 lu_object_put(env, luch);
3570                                 CERROR("Unable to get osd_object\n");
3571                                 child = ERR_PTR(-ENOENT);
3572                         }
3573                 } else {
3574                         LU_OBJECT_DEBUG(D_ERROR, env, luch,
3575                                         "lu_object does not exists "DFID"\n",
3576                                         PFID(fid));
3577                         lu_object_put(env, luch);
3578                         child = ERR_PTR(-ENOENT);
3579                 }
3580         } else
3581                 child = (void *)luch;
3582
3583         return child;
3584 }
3585
3586 /**
3587  * Put the osd object once done with it.
3588  *
3589  * \param obj osd object that needs to be put
3590  */
3591 static inline void osd_object_put(const struct lu_env *env,
3592                                   struct osd_object *obj)
3593 {
3594         lu_object_put(env, &obj->oo_dt.do_lu);
3595 }
3596
3597 static int osd_index_declare_ea_insert(const struct lu_env *env,
3598                                        struct dt_object *dt,
3599                                        const struct dt_rec *rec,
3600                                        const struct dt_key *key,
3601                                        struct thandle *handle)
3602 {
3603         struct osd_thandle *oh;
3604         struct inode       *inode;
3605         int                 rc;
3606         ENTRY;
3607
3608         LASSERT(dt_object_exists(dt));
3609         LASSERT(handle != NULL);
3610
3611         oh = container_of0(handle, struct osd_thandle, ot_super);
3612         LASSERT(oh->ot_handle == NULL);
3613
3614         OSD_DECLARE_OP(oh, insert);
3615         oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
3616
3617         inode = osd_dt_obj(dt)->oo_inode;
3618         LASSERT(inode);
3619
3620         /* We ignore block quota on meta pool (MDTs), so needn't
3621          * calculate how many blocks will be consumed by this index
3622          * insert */
3623         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
3624                                    true, true, NULL, false);
3625         RETURN(rc);
3626 }
3627
3628 /**
3629  * Index add function for interoperability mode (b11826).
3630  * It will add the directory entry.This entry is needed to
3631  * maintain name->fid mapping.
3632  *
3633  * \param key it is key i.e. file entry to be inserted
3634  * \param rec it is value of given key i.e. fid
3635  *
3636  * \retval   0, on success
3637  * \retval -ve, on error
3638  */
3639 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
3640                                const struct dt_rec *rec,
3641                                const struct dt_key *key, struct thandle *th,
3642                                struct lustre_capa *capa, int ignore_quota)
3643 {
3644         struct osd_object *obj   = osd_dt_obj(dt);
3645         struct lu_fid     *fid   = (struct lu_fid *) rec;
3646         const char        *name  = (const char *)key;
3647         struct osd_object *child;
3648 #ifdef HAVE_QUOTA_SUPPORT
3649         cfs_cap_t          save  = cfs_curproc_cap_pack();
3650 #endif
3651         int                rc;
3652
3653         ENTRY;
3654
3655         LASSERT(osd_invariant(obj));
3656         LASSERT(dt_object_exists(dt));
3657         LASSERT(th != NULL);
3658
3659         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3660                 RETURN(-EACCES);
3661
3662         child = osd_object_find(env, dt, fid);
3663         if (!IS_ERR(child)) {
3664 #ifdef HAVE_QUOTA_SUPPORT
3665                 if (ignore_quota)
3666                         cfs_cap_raise(CFS_CAP_SYS_RESOURCE);
3667                 else
3668                         cfs_cap_lower(CFS_CAP_SYS_RESOURCE);
3669 #endif
3670                 rc = osd_ea_add_rec(env, obj, child->oo_inode, name, rec, th);
3671 #ifdef HAVE_QUOTA_SUPPORT
3672                 cfs_curproc_cap_unpack(save);
3673 #endif
3674                 osd_object_put(env, child);
3675         } else {
3676                 rc = PTR_ERR(child);
3677         }
3678
3679         LASSERT(osd_invariant(obj));
3680         RETURN(rc);
3681 }
3682
3683 /**
3684  *  Initialize osd Iterator for given osd index object.
3685  *
3686  *  \param  dt      osd index object
3687  */
3688
3689 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
3690                                      struct dt_object *dt,
3691                                      __u32 unused,
3692                                      struct lustre_capa *capa)
3693 {
3694         struct osd_it_iam      *it;
3695         struct osd_thread_info *oti = osd_oti_get(env);
3696         struct osd_object      *obj = osd_dt_obj(dt);
3697         struct lu_object       *lo  = &dt->do_lu;
3698         struct iam_path_descr  *ipd;
3699         struct iam_container   *bag = &obj->oo_dir->od_container;
3700
3701         LASSERT(lu_object_exists(lo));
3702
3703         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
3704                 return ERR_PTR(-EACCES);
3705
3706         it = &oti->oti_it;
3707         ipd = osd_it_ipd_get(env, bag);
3708         if (likely(ipd != NULL)) {
3709                 it->oi_obj = obj;
3710                 it->oi_ipd = ipd;
3711                 lu_object_get(lo);
3712                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
3713                 return (struct dt_it *)it;
3714         }
3715         return ERR_PTR(-ENOMEM);
3716 }
3717
3718 /**
3719  * free given Iterator.
3720  */
3721
3722 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
3723 {
3724         struct osd_it_iam *it = (struct osd_it_iam *)di;
3725         struct osd_object *obj = it->oi_obj;
3726
3727         iam_it_fini(&it->oi_it);
3728         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
3729         lu_object_put(env, &obj->oo_dt.do_lu);
3730 }
3731
3732 /**
3733  *  Move Iterator to record specified by \a key
3734  *
3735  *  \param  di      osd iterator
3736  *  \param  key     key for index
3737  *
3738  *  \retval +ve  di points to record with least key not larger than key
3739  *  \retval  0   di points to exact matched key
3740  *  \retval -ve  failure
3741  */
3742
3743 static int osd_it_iam_get(const struct lu_env *env,
3744                           struct dt_it *di, const struct dt_key *key)
3745 {
3746         struct osd_thread_info  *oti = osd_oti_get(env);
3747         struct osd_it_iam       *it = (struct osd_it_iam *)di;
3748
3749         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
3750                 /* swab quota uid/gid */
3751                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3752                 key = (struct dt_key *)&oti->oti_quota_id;
3753         }
3754
3755         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
3756 }
3757
3758 /**
3759  *  Release Iterator
3760  *
3761  *  \param  di      osd iterator
3762  */
3763
3764 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
3765 {
3766         struct osd_it_iam *it = (struct osd_it_iam *)di;
3767
3768         iam_it_put(&it->oi_it);
3769 }
3770
3771 /**
3772  *  Move iterator by one record
3773  *
3774  *  \param  di      osd iterator
3775  *
3776  *  \retval +1   end of container reached
3777  *  \retval  0   success
3778  *  \retval -ve  failure
3779  */
3780
3781 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
3782 {
3783         struct osd_it_iam *it = (struct osd_it_iam *)di;
3784
3785         return iam_it_next(&it->oi_it);
3786 }
3787
3788 /**
3789  * Return pointer to the key under iterator.
3790  */
3791
3792 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
3793                                  const struct dt_it *di)
3794 {
3795         struct osd_thread_info *oti = osd_oti_get(env);
3796         struct osd_it_iam      *it = (struct osd_it_iam *)di;
3797         struct osd_object      *obj = it->oi_obj;
3798         struct dt_key          *key;
3799
3800         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
3801
3802         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
3803                 /* swab quota uid/gid */
3804                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
3805                 key = (struct dt_key *)&oti->oti_quota_id;
3806         }
3807
3808         return key;
3809 }
3810
3811 /**
3812  * Return size of key under iterator (in bytes)
3813  */
3814
3815 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
3816 {
3817         struct osd_it_iam *it = (struct osd_it_iam *)di;
3818
3819         return iam_it_key_size(&it->oi_it);
3820 }
3821
3822 static inline void osd_it_append_attrs(struct lu_dirent *ent, __u32 attr,
3823                                        int len, __u16 type)
3824 {
3825         struct luda_type *lt;
3826         const unsigned    align = sizeof(struct luda_type) - 1;
3827
3828         /* check if file type is required */
3829         if (attr & LUDA_TYPE) {
3830                         len = (len + align) & ~align;
3831
3832                         lt = (void *) ent->lde_name + len;
3833                         lt->lt_type = cpu_to_le16(CFS_DTTOIF(type));
3834                         ent->lde_attrs |= LUDA_TYPE;
3835         }
3836
3837         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
3838 }
3839
3840 /**
3841  * build lu direct from backend fs dirent.
3842  */
3843
3844 static inline void osd_it_pack_dirent(struct lu_dirent *ent,
3845                                       struct lu_fid *fid, __u64 offset,
3846                                       char *name, __u16 namelen,
3847                                       __u16 type, __u32 attr)
3848 {
3849         fid_cpu_to_le(&ent->lde_fid, fid);
3850         ent->lde_attrs = LUDA_FID;
3851
3852         ent->lde_hash = cpu_to_le64(offset);
3853         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
3854
3855         strncpy(ent->lde_name, name, namelen);
3856         ent->lde_namelen = cpu_to_le16(namelen);
3857
3858         /* append lustre attributes */
3859         osd_it_append_attrs(ent, attr, namelen, type);
3860 }
3861
3862 /**
3863  * Return pointer to the record under iterator.
3864  */
3865 static int osd_it_iam_rec(const struct lu_env *env,
3866                           const struct dt_it *di,
3867                           struct dt_rec *dtrec, __u32 attr)
3868 {
3869         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
3870         struct osd_thread_info *info = osd_oti_get(env);
3871         ENTRY;
3872
3873         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
3874                 const struct osd_fid_pack *rec;
3875                 struct lu_fid             *fid = &info->oti_fid;
3876                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
3877                 char                      *name;
3878                 int                        namelen;
3879                 __u64                      hash;
3880                 int                        rc;
3881
3882                 name = (char *)iam_it_key_get(&it->oi_it);
3883                 if (IS_ERR(name))
3884                         RETURN(PTR_ERR(name));
3885
3886                 namelen = iam_it_key_size(&it->oi_it);
3887
3888                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
3889                 if (IS_ERR(rec))
3890                         RETURN(PTR_ERR(rec));
3891
3892                 rc = osd_fid_unpack(fid, rec);
3893                 if (rc)
3894                         RETURN(rc);
3895
3896                 hash = iam_it_store(&it->oi_it);
3897
3898                 /* IAM does not store object type in IAM index (dir) */
3899                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
3900                                    0, LUDA_FID);
3901         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
3902                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
3903                            (struct iam_rec *)dtrec);
3904                 osd_quota_unpack(it->oi_obj, dtrec);
3905         } else {
3906                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
3907                            (struct iam_rec *)dtrec);
3908         }
3909
3910         RETURN(0);
3911 }
3912
3913 /**
3914  * Returns cookie for current Iterator position.
3915  */
3916 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
3917 {
3918         struct osd_it_iam *it = (struct osd_it_iam *)di;
3919
3920         return iam_it_store(&it->oi_it);
3921 }
3922
3923 /**
3924  * Restore iterator from cookie.
3925  *
3926  * \param  di      osd iterator
3927  * \param  hash    Iterator location cookie
3928  *
3929  * \retval +ve  di points to record with least key not larger than key.
3930  * \retval  0   di points to exact matched key
3931  * \retval -ve  failure
3932  */
3933
3934 static int osd_it_iam_load(const struct lu_env *env,
3935                            const struct dt_it *di, __u64 hash)
3936 {
3937         struct osd_it_iam *it = (struct osd_it_iam *)di;
3938
3939         return iam_it_load(&it->oi_it, hash);
3940 }
3941
3942 static const struct dt_index_operations osd_index_iam_ops = {
3943         .dio_lookup         = osd_index_iam_lookup,
3944         .dio_declare_insert = osd_index_declare_iam_insert,
3945         .dio_insert         = osd_index_iam_insert,
3946         .dio_declare_delete = osd_index_declare_iam_delete,
3947         .dio_delete         = osd_index_iam_delete,
3948         .dio_it     = {
3949                 .init     = osd_it_iam_init,
3950                 .fini     = osd_it_iam_fini,
3951                 .get      = osd_it_iam_get,
3952                 .put      = osd_it_iam_put,
3953                 .next     = osd_it_iam_next,
3954                 .key      = osd_it_iam_key,
3955                 .key_size = osd_it_iam_key_size,
3956                 .rec      = osd_it_iam_rec,
3957                 .store    = osd_it_iam_store,
3958                 .load     = osd_it_iam_load
3959         }
3960 };
3961
3962 /**
3963  * Creates or initializes iterator context.
3964  *
3965  * \retval struct osd_it_ea, iterator structure on success
3966  *
3967  */
3968 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
3969                                     struct dt_object *dt,
3970                                     __u32 attr,
3971                                     struct lustre_capa *capa)
3972 {
3973         struct osd_object       *obj  = osd_dt_obj(dt);
3974         struct osd_thread_info  *info = osd_oti_get(env);
3975         struct osd_it_ea        *it   = &info->oti_it_ea;
3976         struct lu_object        *lo   = &dt->do_lu;
3977         struct dentry           *obj_dentry = &info->oti_it_dentry;
3978         ENTRY;
3979         LASSERT(lu_object_exists(lo));
3980
3981         obj_dentry->d_inode = obj->oo_inode;
3982         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
3983         obj_dentry->d_name.hash = 0;
3984
3985         it->oie_rd_dirent       = 0;
3986         it->oie_it_dirent       = 0;
3987         it->oie_dirent          = NULL;
3988         it->oie_buf             = info->oti_it_ea_buf;
3989         it->oie_obj             = obj;
3990         it->oie_file.f_pos      = 0;
3991         it->oie_file.f_dentry   = obj_dentry;
3992         if (attr & LUDA_64BITHASH)
3993                 it->oie_file.f_mode |= FMODE_64BITHASH;
3994         else
3995                 it->oie_file.f_mode |= FMODE_32BITHASH;
3996         it->oie_file.f_mapping    = obj->oo_inode->i_mapping;
3997         it->oie_file.f_op         = obj->oo_inode->i_fop;
3998         it->oie_file.private_data = NULL;
3999         lu_object_get(lo);
4000         RETURN((struct dt_it *) it);
4001 }
4002
4003 /**
4004  * Destroy or finishes iterator context.
4005  *
4006  * \param di iterator structure to be destroyed
4007  */
4008 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
4009 {
4010         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4011         struct osd_object    *obj  = it->oie_obj;
4012         struct inode       *inode  = obj->oo_inode;
4013
4014         ENTRY;
4015         it->oie_file.f_op->release(inode, &it->oie_file);
4016         lu_object_put(env, &obj->oo_dt.do_lu);
4017         EXIT;
4018 }
4019
4020 /**
4021  * It position the iterator at given key, so that next lookup continues from
4022  * that key Or it is similar to dio_it->load() but based on a key,
4023  * rather than file position.
4024  *
4025  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
4026  * to the beginning.
4027  *
4028  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
4029  */
4030 static int osd_it_ea_get(const struct lu_env *env,
4031                          struct dt_it *di, const struct dt_key *key)
4032 {
4033         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4034
4035         ENTRY;
4036         LASSERT(((const char *)key)[0] == '\0');
4037         it->oie_file.f_pos      = 0;
4038         it->oie_rd_dirent       = 0;
4039         it->oie_it_dirent       = 0;
4040         it->oie_dirent          = NULL;
4041
4042         RETURN(+1);
4043 }
4044
4045 /**
4046  * Does nothing
4047  */
4048 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
4049 {
4050 }
4051
4052 /**
4053  * It is called internally by ->readdir(). It fills the
4054  * iterator's in-memory data structure with required
4055  * information i.e. name, namelen, rec_size etc.
4056  *
4057  * \param buf in which information to be filled in.
4058  * \param name name of the file in given dir
4059  *
4060  * \retval 0 on success
4061  * \retval 1 on buffer full
4062  */
4063 static int osd_ldiskfs_filldir(char *buf, const char *name, int namelen,
4064                                loff_t offset, __u64 ino,
4065                                unsigned d_type)
4066 {
4067         struct osd_it_ea        *it   = (struct osd_it_ea *)buf;
4068         struct osd_it_ea_dirent *ent  = it->oie_dirent;
4069         struct lu_fid           *fid  = &ent->oied_fid;
4070         struct osd_fid_pack     *rec;
4071         ENTRY;
4072
4073         /* this should never happen */
4074         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
4075                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
4076                 RETURN(-EIO);
4077         }
4078
4079         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
4080             OSD_IT_EA_BUFSIZE)
4081                 RETURN(1);
4082
4083         if (d_type & LDISKFS_DIRENT_LUFID) {
4084                 rec = (struct osd_fid_pack*) (name + namelen + 1);
4085
4086                 if (osd_fid_unpack(fid, rec) != 0)
4087                         fid_zero(fid);
4088
4089                 d_type &= ~LDISKFS_DIRENT_LUFID;
4090         } else {
4091                 fid_zero(fid);
4092         }
4093
4094         ent->oied_ino     = ino;
4095         ent->oied_off     = offset;
4096         ent->oied_namelen = namelen;
4097         ent->oied_type    = d_type;
4098
4099         memcpy(ent->oied_name, name, namelen);
4100
4101         it->oie_rd_dirent++;
4102         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
4103         RETURN(0);
4104 }
4105
4106 /**
4107  * Calls ->readdir() to load a directory entry at a time
4108  * and stored it in iterator's in-memory data structure.
4109  *
4110  * \param di iterator's in memory structure
4111  *
4112  * \retval   0 on success
4113  * \retval -ve on error
4114  */
4115 static int osd_ldiskfs_it_fill(const struct lu_env *env,
4116                                const struct dt_it *di)
4117 {
4118         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
4119         struct osd_object  *obj   = it->oie_obj;
4120         struct inode       *inode = obj->oo_inode;
4121         struct htree_lock  *hlock = NULL;
4122         int                 result = 0;
4123
4124         ENTRY;
4125         it->oie_dirent = it->oie_buf;
4126         it->oie_rd_dirent = 0;
4127
4128         if (obj->oo_hl_head != NULL) {
4129                 hlock = osd_oti_get(env)->oti_hlock;
4130                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4131                                    inode, LDISKFS_HLOCK_READDIR);
4132         } else {
4133                 cfs_down_read(&obj->oo_ext_idx_sem);
4134         }
4135
4136         result = inode->i_fop->readdir(&it->oie_file, it,
4137                                        (filldir_t) osd_ldiskfs_filldir);
4138
4139         if (hlock != NULL)
4140                 ldiskfs_htree_unlock(hlock);
4141         else
4142                 cfs_up_read(&obj->oo_ext_idx_sem);
4143
4144         if (it->oie_rd_dirent == 0) {
4145                 result = -EIO;
4146         } else {
4147                 it->oie_dirent = it->oie_buf;
4148                 it->oie_it_dirent = 1;
4149         }
4150
4151         RETURN(result);
4152 }
4153
4154 /**
4155  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4156  * to load a directory entry at a time and stored it in
4157  * iterator's in-memory data structure.
4158  *
4159  * \param di iterator's in memory structure
4160  *
4161  * \retval +ve iterator reached to end
4162  * \retval   0 iterator not reached to end
4163  * \retval -ve on error
4164  */
4165 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
4166 {
4167         struct osd_it_ea *it = (struct osd_it_ea *)di;
4168         int rc;
4169
4170         ENTRY;
4171
4172         if (it->oie_it_dirent < it->oie_rd_dirent) {
4173                 it->oie_dirent =
4174                         (void *) it->oie_dirent +
4175                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
4176                                        it->oie_dirent->oied_namelen);
4177                 it->oie_it_dirent++;
4178                 RETURN(0);
4179         } else {
4180                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
4181                         rc = +1;
4182                 else
4183                         rc = osd_ldiskfs_it_fill(env, di);
4184         }
4185
4186         RETURN(rc);
4187 }
4188
4189 /**
4190  * Returns the key at current position from iterator's in memory structure.
4191  *
4192  * \param di iterator's in memory structure
4193  *
4194  * \retval key i.e. struct dt_key on success
4195  */
4196 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
4197                                     const struct dt_it *di)
4198 {
4199         struct osd_it_ea *it = (struct osd_it_ea *)di;
4200
4201         return (struct dt_key *)it->oie_dirent->oied_name;
4202 }
4203
4204 /**
4205  * Returns the key's size at current position from iterator's in memory structure.
4206  *
4207  * \param di iterator's in memory structure
4208  *
4209  * \retval key_size i.e. struct dt_key on success
4210  */
4211 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
4212 {
4213         struct osd_it_ea *it = (struct osd_it_ea *)di;
4214
4215         return it->oie_dirent->oied_namelen;
4216 }
4217
4218
4219 /**
4220  * Returns the value (i.e. fid/igif) at current position from iterator's
4221  * in memory structure.
4222  *
4223  * \param di struct osd_it_ea, iterator's in memory structure
4224  * \param attr attr requested for dirent.
4225  * \param lde lustre dirent
4226  *
4227  * \retval   0 no error and \param lde has correct lustre dirent.
4228  * \retval -ve on error
4229  */
4230 static inline int osd_it_ea_rec(const struct lu_env *env,
4231                                 const struct dt_it *di,
4232                                 struct dt_rec *dtrec, __u32 attr)
4233 {
4234         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
4235         struct osd_object      *obj   = it->oie_obj;
4236         struct osd_device      *dev   = osd_obj2dev(obj);
4237         struct osd_scrub       *scrub = &dev->od_scrub;
4238         struct scrub_file      *sf    = &scrub->os_file;
4239         struct osd_thread_info *oti   = osd_oti_get(env);
4240         struct osd_idmap_cache *oic   = &oti->oti_cache;
4241         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
4242         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
4243         __u32                   ino   = it->oie_dirent->oied_ino;
4244         int                     rc    = 0;
4245         ENTRY;
4246
4247         if (!fid_is_sane(fid)) {
4248                 rc = osd_ea_fid_get(env, obj, ino, fid, &oic->oic_lid);
4249                 if (rc != 0)
4250                         RETURN(rc);
4251         } else {
4252                 osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
4253         }
4254
4255         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
4256                            it->oie_dirent->oied_name,
4257                            it->oie_dirent->oied_namelen,
4258                            it->oie_dirent->oied_type, attr);
4259         if (!fid_is_norm(fid)) {
4260                 fid_zero(&oic->oic_fid);
4261                 RETURN(0);
4262         }
4263
4264         oic->oic_fid = *fid;
4265         if ((scrub->os_pos_current <= ino) &&
4266             (sf->sf_flags & SF_INCONSISTENT ||
4267              ldiskfs_test_bit(osd_oi_fid2idx(dev, fid), sf->sf_oi_bitmap)))
4268                 rc = osd_consistency_check(oti, dev, oic);
4269
4270         RETURN(rc);
4271 }
4272
4273 /**
4274  * Returns a cookie for current position of the iterator head, so that
4275  * user can use this cookie to load/start the iterator next time.
4276  *
4277  * \param di iterator's in memory structure
4278  *
4279  * \retval cookie for current position, on success
4280  */
4281 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
4282 {
4283         struct osd_it_ea *it = (struct osd_it_ea *)di;
4284
4285         return it->oie_dirent->oied_off;
4286 }
4287
4288 /**
4289  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4290  * to load a directory entry at a time and stored it i inn,
4291  * in iterator's in-memory data structure.
4292  *
4293  * \param di struct osd_it_ea, iterator's in memory structure
4294  *
4295  * \retval +ve on success
4296  * \retval -ve on error
4297  */
4298 static int osd_it_ea_load(const struct lu_env *env,
4299                           const struct dt_it *di, __u64 hash)
4300 {
4301         struct osd_it_ea *it = (struct osd_it_ea *)di;
4302         int rc;
4303
4304         ENTRY;
4305         it->oie_file.f_pos = hash;
4306
4307         rc =  osd_ldiskfs_it_fill(env, di);
4308         if (rc == 0)
4309                 rc = +1;
4310
4311         RETURN(rc);
4312 }
4313
4314 /**
4315  * Index lookup function for interoperability mode (b11826).
4316  *
4317  * \param key,  key i.e. file name to be searched
4318  *
4319  * \retval +ve, on success
4320  * \retval -ve, on error
4321  */
4322 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
4323                                struct dt_rec *rec, const struct dt_key *key,
4324                                struct lustre_capa *capa)
4325 {
4326         struct osd_object *obj = osd_dt_obj(dt);
4327         int rc = 0;
4328
4329         ENTRY;
4330
4331         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
4332         LINVRNT(osd_invariant(obj));
4333
4334         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
4335                 return -EACCES;
4336
4337         rc = osd_ea_lookup_rec(env, obj, rec, key);
4338
4339         if (rc == 0)
4340                 rc = +1;
4341         RETURN(rc);
4342 }
4343
4344 /**
4345  * Index and Iterator operations for interoperability
4346  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
4347  */
4348 static const struct dt_index_operations osd_index_ea_ops = {
4349         .dio_lookup         = osd_index_ea_lookup,
4350         .dio_declare_insert = osd_index_declare_ea_insert,
4351         .dio_insert         = osd_index_ea_insert,
4352         .dio_declare_delete = osd_index_declare_ea_delete,
4353         .dio_delete         = osd_index_ea_delete,
4354         .dio_it     = {
4355                 .init     = osd_it_ea_init,
4356                 .fini     = osd_it_ea_fini,
4357                 .get      = osd_it_ea_get,
4358                 .put      = osd_it_ea_put,
4359                 .next     = osd_it_ea_next,
4360                 .key      = osd_it_ea_key,
4361                 .key_size = osd_it_ea_key_size,
4362                 .rec      = osd_it_ea_rec,
4363                 .store    = osd_it_ea_store,
4364                 .load     = osd_it_ea_load
4365         }
4366 };
4367
4368 static void *osd_key_init(const struct lu_context *ctx,
4369                           struct lu_context_key *key)
4370 {
4371         struct osd_thread_info *info;
4372
4373         OBD_ALLOC_PTR(info);
4374         if (info == NULL)
4375                 return ERR_PTR(-ENOMEM);
4376
4377         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
4378         if (info->oti_it_ea_buf == NULL)
4379                 goto out_free_info;
4380
4381         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
4382
4383         info->oti_hlock = ldiskfs_htree_lock_alloc();
4384         if (info->oti_hlock == NULL)
4385                 goto out_free_ea;
4386
4387         return info;
4388
4389  out_free_ea:
4390         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
4391  out_free_info:
4392         OBD_FREE_PTR(info);
4393         return ERR_PTR(-ENOMEM);
4394 }
4395
4396 static void osd_key_fini(const struct lu_context *ctx,
4397                          struct lu_context_key *key, void* data)
4398 {
4399         struct osd_thread_info *info = data;
4400
4401         if (info->oti_hlock != NULL)
4402                 ldiskfs_htree_lock_free(info->oti_hlock);
4403         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
4404         OBD_FREE_PTR(info);
4405 }
4406
4407 static void osd_key_exit(const struct lu_context *ctx,
4408                          struct lu_context_key *key, void *data)
4409 {
4410         struct osd_thread_info *info = data;
4411
4412         LASSERT(info->oti_r_locks == 0);
4413         LASSERT(info->oti_w_locks == 0);
4414         LASSERT(info->oti_txns    == 0);
4415 }
4416
4417 /* type constructor/destructor: osd_type_init, osd_type_fini */
4418 LU_TYPE_INIT_FINI(osd, &osd_key);
4419
4420 struct lu_context_key osd_key = {
4421         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
4422         .lct_init = osd_key_init,
4423         .lct_fini = osd_key_fini,
4424         .lct_exit = osd_key_exit
4425 };
4426
4427
4428 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
4429                            const char *name, struct lu_device *next)
4430 {
4431         struct osd_device *osd = osd_dev(d);
4432
4433         strncpy(osd->od_svname, name, MAX_OBD_NAME);
4434         return osd_procfs_init(osd, name);
4435 }
4436
4437 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
4438 {
4439         ENTRY;
4440
4441         osd_scrub_cleanup(env, o);
4442
4443         if (o->od_fsops) {
4444                 fsfilt_put_ops(o->od_fsops);
4445                 o->od_fsops = NULL;
4446         }
4447
4448         /* shutdown quota slave instance associated with the device */
4449         if (o->od_quota_slave != NULL) {
4450                 qsd_fini(env, o->od_quota_slave);
4451                 o->od_quota_slave = NULL;
4452         }
4453
4454         RETURN(0);
4455 }
4456
4457 static int osd_mount(const struct lu_env *env,
4458                      struct osd_device *o, struct lustre_cfg *cfg)
4459 {
4460         const char              *name  = lustre_cfg_string(cfg, 0);
4461         const char              *dev  = lustre_cfg_string(cfg, 1);
4462         const char              *opts;
4463         unsigned long            page, s_flags, lmd_flags = 0;
4464         struct page             *__page;
4465         struct file_system_type *type;
4466         char                    *options = NULL;
4467         char                    *str;
4468         int                       rc = 0;
4469         ENTRY;
4470
4471         if (o->od_mnt != NULL)
4472                 RETURN(0);
4473
4474         o->od_fsops = fsfilt_get_ops(mt_str(LDD_MT_LDISKFS));
4475         if (o->od_fsops == NULL) {
4476                 CERROR("Can't find fsfilt_ldiskfs\n");
4477                 RETURN(-ENOTSUPP);
4478         }
4479
4480         OBD_PAGE_ALLOC(__page, CFS_ALLOC_STD);
4481         if (__page == NULL)
4482                 GOTO(out, rc = -ENOMEM);
4483
4484         str = lustre_cfg_string(cfg, 2);
4485         s_flags = simple_strtoul(str, NULL, 0);
4486         str = strstr(str, ":");
4487         if (str)
4488                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
4489         opts = lustre_cfg_string(cfg, 3);
4490         page = (unsigned long)cfs_page_address(__page);
4491         options = (char *)page;
4492         *options = '\0';
4493         if (opts == NULL)
4494                 strcat(options, "user_xattr,acl");
4495         else
4496                 strcat(options, opts);
4497
4498         /* Glom up mount options */
4499         if (*options != '\0')
4500                 strcat(options, ",");
4501         strlcat(options, "no_mbcache", CFS_PAGE_SIZE);
4502
4503         type = get_fs_type("ldiskfs");
4504         if (!type) {
4505                 CERROR("%s: cannot find ldiskfs module\n", name);
4506                 GOTO(out, rc = -ENODEV);
4507         }
4508
4509         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
4510         cfs_module_put(type->owner);
4511
4512         if (IS_ERR(o->od_mnt)) {
4513                 rc = PTR_ERR(o->od_mnt);
4514                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
4515                 o->od_mnt = NULL;
4516                 GOTO(out, rc);
4517         }
4518
4519         if (lvfs_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
4520                 CERROR("%s: underlying device %s is marked as read-only. "
4521                        "Setup failed\n", name, dev);
4522                 mntput(o->od_mnt);
4523                 o->od_mnt = NULL;
4524                 GOTO(out, rc = -EROFS);
4525         }
4526
4527         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
4528             LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
4529                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
4530                 mntput(o->od_mnt);
4531                 o->od_mnt = NULL;
4532                 GOTO(out, rc = -EINVAL);
4533         }
4534
4535         if (lmd_flags & LMD_FLG_IAM) {
4536                 o->od_iop_mode = 0;
4537                 LCONSOLE_WARN("%s: OSD: IAM mode enabled\n", name);
4538         } else
4539                 o->od_iop_mode = 1;
4540         if (lmd_flags & LMD_FLG_NOSCRUB)
4541                 o->od_scrub.os_no_scrub = 1;
4542
4543 out:
4544         if (__page)
4545                 OBD_PAGE_FREE(__page);
4546         if (rc)
4547                 fsfilt_put_ops(o->od_fsops);
4548
4549         RETURN(rc);
4550 }
4551
4552 static struct lu_device *osd_device_fini(const struct lu_env *env,
4553                                          struct lu_device *d)
4554 {
4555         int rc;
4556         ENTRY;
4557
4558         rc = osd_shutdown(env, osd_dev(d));
4559
4560         osd_compat_fini(osd_dev(d));
4561
4562         shrink_dcache_sb(osd_sb(osd_dev(d)));
4563         osd_sync(env, lu2dt_dev(d));
4564
4565         rc = osd_procfs_fini(osd_dev(d));
4566         if (rc) {
4567                 CERROR("proc fini error %d \n", rc);
4568                 RETURN (ERR_PTR(rc));
4569         }
4570
4571         if (osd_dev(d)->od_mnt) {
4572                 mntput(osd_dev(d)->od_mnt);
4573                 osd_dev(d)->od_mnt = NULL;
4574         }
4575
4576         RETURN(NULL);
4577 }
4578
4579 static int osd_device_init0(const struct lu_env *env,
4580                             struct osd_device *o,
4581                             struct lustre_cfg *cfg)
4582 {
4583         struct lu_device        *l = osd2lu_dev(o);
4584         struct osd_thread_info *info;
4585         int                     rc;
4586
4587         /* if the module was re-loaded, env can loose its keys */
4588         rc = lu_env_refill((struct lu_env *) env);
4589         if (rc)
4590                 GOTO(out, rc);
4591         info = osd_oti_get(env);
4592         LASSERT(info);
4593
4594         l->ld_ops = &osd_lu_ops;
4595         o->od_dt_dev.dd_ops = &osd_dt_ops;
4596
4597         cfs_spin_lock_init(&o->od_osfs_lock);
4598         cfs_mutex_init(&o->od_otable_mutex);
4599         o->od_osfs_age = cfs_time_shift_64(-1000);
4600
4601         o->od_capa_hash = init_capa_hash();
4602         if (o->od_capa_hash == NULL)
4603                 GOTO(out, rc = -ENOMEM);
4604
4605         o->od_read_cache = 1;
4606         o->od_writethrough_cache = 1;
4607
4608         rc = osd_mount(env, o, cfg);
4609         if (rc)
4610                 GOTO(out_capa, rc);
4611
4612         /* setup scrub, including OI files initialization */
4613         rc = osd_scrub_setup(env, o);
4614         if (rc < 0)
4615                 GOTO(out_mnt, rc);
4616
4617         strncpy(o->od_svname, lustre_cfg_string(cfg, 4),
4618                         sizeof(o->od_svname) - 1);
4619
4620         if (strstr(o->od_svname, "-OST")) {
4621                 rc = osd_compat_init(o);
4622                 if (rc != 0)
4623                         GOTO(out_mnt, rc);
4624         }
4625
4626         rc = lu_site_init(&o->od_site, l);
4627         if (rc)
4628                 GOTO(out_compat, rc);
4629
4630         rc = lu_site_init_finish(&o->od_site);
4631         if (rc)
4632                 GOTO(out_compat, rc);
4633
4634         rc = osd_procfs_init(o, o->od_svname);
4635         if (rc != 0) {
4636                 CERROR("%s: can't initialize procfs: rc = %d\n",
4637                        o->od_svname, rc);
4638                 GOTO(out_compat, rc);
4639         }
4640
4641         LASSERT(l->ld_site->ls_linkage.next && l->ld_site->ls_linkage.prev);
4642
4643         RETURN(0);
4644 out_compat:
4645         osd_compat_fini(o);
4646 out_mnt:
4647         osd_oi_fini(info, o);
4648         osd_shutdown(env, o);
4649         mntput(o->od_mnt);
4650         o->od_mnt = NULL;
4651 out_capa:
4652         cleanup_capa_hash(o->od_capa_hash);
4653 out:
4654         RETURN(rc);
4655 }
4656
4657 static struct lu_device *osd_device_alloc(const struct lu_env *env,
4658                                           struct lu_device_type *t,
4659                                           struct lustre_cfg *cfg)
4660 {
4661         struct osd_device *o;
4662         int                rc;
4663
4664         OBD_ALLOC_PTR(o);
4665         if (o == NULL)
4666                 return ERR_PTR(-ENOMEM);
4667
4668         rc = dt_device_init(&o->od_dt_dev, t);
4669         if (rc == 0) {
4670                 rc = osd_device_init0(env, o, cfg);
4671                 if (rc)
4672                         dt_device_fini(&o->od_dt_dev);
4673         }
4674
4675         if (unlikely(rc != 0))
4676                 OBD_FREE_PTR(o);
4677
4678         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
4679 }
4680
4681 static struct lu_device *osd_device_free(const struct lu_env *env,
4682                                          struct lu_device *d)
4683 {
4684         struct osd_device *o = osd_dev(d);
4685         ENTRY;
4686
4687         cleanup_capa_hash(o->od_capa_hash);
4688         /* XXX: make osd top device in order to release reference */
4689         d->ld_site->ls_top_dev = d;
4690         lu_site_purge(env, d->ld_site, -1);
4691         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
4692                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
4693                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
4694         }
4695         lu_site_fini(&o->od_site);
4696         dt_device_fini(&o->od_dt_dev);
4697         OBD_FREE_PTR(o);
4698         RETURN(NULL);
4699 }
4700
4701 static int osd_process_config(const struct lu_env *env,
4702                               struct lu_device *d, struct lustre_cfg *cfg)
4703 {
4704         struct osd_device *o = osd_dev(d);
4705         int err;
4706         ENTRY;
4707
4708         switch(cfg->lcfg_command) {
4709         case LCFG_SETUP:
4710                 err = osd_mount(env, o, cfg);
4711                 break;
4712         case LCFG_CLEANUP:
4713                 lu_dev_del_linkage(d->ld_site, d);
4714                 err = osd_shutdown(env, o);
4715                 break;
4716         default:
4717                 err = -ENOSYS;
4718         }
4719
4720         RETURN(err);
4721 }
4722
4723 static int osd_recovery_complete(const struct lu_env *env,
4724                                  struct lu_device *d)
4725 {
4726         RETURN(0);
4727 }
4728
4729 /*
4730  * we use exports to track all osd users
4731  */
4732 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
4733                            struct obd_device *obd, struct obd_uuid *cluuid,
4734                            struct obd_connect_data *data, void *localdata)
4735 {
4736         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
4737         struct lustre_handle  conn;
4738         int                   rc;
4739         ENTRY;
4740
4741         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
4742
4743         rc = class_connect(&conn, obd, cluuid);
4744         if (rc)
4745                 RETURN(rc);
4746
4747         *exp = class_conn2export(&conn);
4748
4749         cfs_spin_lock(&osd->od_osfs_lock);
4750         osd->od_connects++;
4751         cfs_spin_unlock(&osd->od_osfs_lock);
4752
4753         RETURN(0);
4754 }
4755
4756 /*
4757  * once last export (we don't count self-export) disappeared
4758  * osd can be released
4759  */
4760 static int osd_obd_disconnect(struct obd_export *exp)
4761 {
4762         struct obd_device *obd = exp->exp_obd;
4763         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
4764         int                rc, release = 0;
4765         ENTRY;
4766
4767         /* Only disconnect the underlying layers on the final disconnect. */
4768         cfs_spin_lock(&osd->od_osfs_lock);
4769         osd->od_connects--;
4770         if (osd->od_connects == 0)
4771                 release = 1;
4772         cfs_spin_unlock(&osd->od_osfs_lock);
4773
4774         rc = class_disconnect(exp); /* bz 9811 */
4775
4776         if (rc == 0 && release)
4777                 class_manual_cleanup(obd);
4778         RETURN(rc);
4779 }
4780
4781 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
4782                        struct lu_device *dev)
4783 {
4784         struct osd_device *osd = osd_dev(dev);
4785         int                result = 0;
4786         ENTRY;
4787
4788 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 3, 55, 0)
4789         /* Unfortunately, the current MDD implementation relies on some specific
4790          * code to be executed in the OSD layer. Since OFD now also uses the OSD
4791          * module, we need a way to skip the metadata-specific code when running
4792          * with OFD.
4793          * The hack here is to check the type of the parent device which is
4794          * either MD (i.e. MDD device) with the current MDT stack or DT (i.e.
4795          * OFD device) on an OST. As a reminder, obdfilter does not use the OSD
4796          * layer and still relies on lvfs. This hack won't work any more when
4797          * LOD is landed since LOD is of DT type.
4798          * This code should be removed once the orion MDT changes (LOD/OSP, ...)
4799          * have been landed */
4800         osd->od_is_md = lu_device_is_md(pdev);
4801 #else
4802 #warning "all is_md checks must be removed from osd-ldiskfs"
4803 #endif
4804
4805         if (osd->od_is_md) {
4806                 /* 1. setup local objects */
4807                 result = llo_local_objects_setup(env, lu2md_dev(pdev),
4808                                                  lu2dt_dev(dev));
4809                 if (result)
4810                         RETURN(result);
4811         }
4812
4813         /* 2. setup quota slave instance */
4814         osd->od_quota_slave = qsd_init(env, osd->od_svname, &osd->od_dt_dev,
4815                                        osd->od_proc_entry);
4816         if (IS_ERR(osd->od_quota_slave)) {
4817                 result = PTR_ERR(osd->od_quota_slave);
4818                 osd->od_quota_slave = NULL;
4819         }
4820
4821         RETURN(result);
4822 }
4823
4824 static const struct lu_object_operations osd_lu_obj_ops = {
4825         .loo_object_init      = osd_object_init,
4826         .loo_object_delete    = osd_object_delete,
4827         .loo_object_release   = osd_object_release,
4828         .loo_object_free      = osd_object_free,
4829         .loo_object_print     = osd_object_print,
4830         .loo_object_invariant = osd_object_invariant
4831 };
4832
4833 const struct lu_device_operations osd_lu_ops = {
4834         .ldo_object_alloc      = osd_object_alloc,
4835         .ldo_process_config    = osd_process_config,
4836         .ldo_recovery_complete = osd_recovery_complete,
4837         .ldo_prepare           = osd_prepare,
4838 };
4839
4840 static const struct lu_device_type_operations osd_device_type_ops = {
4841         .ldto_init = osd_type_init,
4842         .ldto_fini = osd_type_fini,
4843
4844         .ldto_start = osd_type_start,
4845         .ldto_stop  = osd_type_stop,
4846
4847         .ldto_device_alloc = osd_device_alloc,
4848         .ldto_device_free  = osd_device_free,
4849
4850         .ldto_device_init    = osd_device_init,
4851         .ldto_device_fini    = osd_device_fini
4852 };
4853
4854 struct lu_device_type osd_device_type = {
4855         .ldt_tags     = LU_DEVICE_DT,
4856         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
4857         .ldt_ops      = &osd_device_type_ops,
4858         .ldt_ctx_tags = LCT_LOCAL,
4859 };
4860
4861 /*
4862  * lprocfs legacy support.
4863  */
4864 static struct obd_ops osd_obd_device_ops = {
4865         .o_owner = THIS_MODULE,
4866         .o_connect      = osd_obd_connect,
4867         .o_disconnect   = osd_obd_disconnect
4868 };
4869
4870 static int __init osd_mod_init(void)
4871 {
4872         struct lprocfs_static_vars lvars;
4873
4874         osd_oi_mod_init();
4875         lprocfs_osd_init_vars(&lvars);
4876         return class_register_type(&osd_obd_device_ops, NULL, lvars.module_vars,
4877                                    LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
4878 }
4879
4880 static void __exit osd_mod_exit(void)
4881 {
4882         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
4883 }
4884
4885 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
4886 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
4887 MODULE_LICENSE("GPL");
4888
4889 cfs_module(osd, "0.1.0", osd_mod_init, osd_mod_exit);