Whamcloud - gitweb
LU-13073 osp: don't block waiting for new objects
[fs/lustre-release.git] / lustre / lod / lod_qos.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright  2009 Sun Microsystems, Inc. All rights reserved
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/lod/lod_qos.c
33  *
34  * Implementation of different allocation algorithm used
35  * to distribute objects and data among OSTs.
36  */
37
38 #define DEBUG_SUBSYSTEM S_LOV
39
40 #include <asm/div64.h>
41 #include <linux/random.h>
42
43 #include <libcfs/libcfs.h>
44 #include <uapi/linux/lustre/lustre_idl.h>
45 #include <lustre_swab.h>
46 #include <obd_class.h>
47
48 #include "lod_internal.h"
49
50 /*
51  * force QoS policy (not RR) to be used for testing purposes
52  */
53 #define FORCE_QOS_
54
55 #define D_QOS   D_OTHER
56
57 #define QOS_DEBUG(fmt, ...)     CDEBUG(D_QOS, fmt, ## __VA_ARGS__)
58 #define QOS_CONSOLE(fmt, ...)   LCONSOLE(D_QOS, fmt, ## __VA_ARGS__)
59
60 #define TGT_BAVAIL(i) (OST_TGT(lod,i)->ltd_statfs.os_bavail * \
61                        OST_TGT(lod,i)->ltd_statfs.os_bsize)
62
63 static inline int lod_statfs_check(struct lu_tgt_descs *ltd,
64                                    struct lu_tgt_desc *tgt)
65 {
66         struct obd_statfs *sfs = &tgt->ltd_statfs;
67
68         if (((sfs->os_state & OS_STATFS_ENOSPC) ||
69             (!ltd->ltd_is_mdt && sfs->os_state & OS_STATFS_ENOINO &&
70              sfs->os_fprecreated == 0)))
71                 return -ENOSPC;
72
73         /* If the OST is readonly then we can't allocate objects there */
74         if (sfs->os_state & OS_STATFS_READONLY)
75                 return -EROFS;
76
77         /* object precreation is skipped on the OST with max_create_count=0 */
78         if (!ltd->ltd_is_mdt && sfs->os_state & OS_STATFS_NOPRECREATE)
79                 return -ENOBUFS;
80
81         return 0;
82 }
83
84 /**
85  * Check whether the target is available for new objects.
86  *
87  * Request statfs data from the given target and verify it's active and not
88  * read-only. If so, then it can be used to place new objects. This
89  * function also maintains the number of active/inactive targets and sets
90  * dirty flags if those numbers change so others can run re-balance procedures.
91  * No external locking is required.
92  *
93  * \param[in] env       execution environment for this thread
94  * \param[in] d         LOD device
95  * \param[in] ltd       target table
96  * \param[in] tgt       target
97  *
98  * \retval 0            if the target is good
99  * \retval negative     negated errno on error
100  */
101 static int lod_statfs_and_check(const struct lu_env *env, struct lod_device *d,
102                                 struct lu_tgt_descs *ltd,
103                                 struct lu_tgt_desc *tgt, __u64 reserve)
104 {
105         struct obd_statfs_info info = { 0 };
106         struct lov_desc *desc = &ltd->ltd_lov_desc;
107         int rc;
108         ENTRY;
109
110         LASSERT(d);
111         LASSERT(tgt);
112
113         info.os_enable_pre = 1;
114         rc = dt_statfs_info(env, tgt->ltd_tgt, &tgt->ltd_statfs, &info);
115         if (rc && rc != -ENOTCONN)
116                 CERROR("%s: statfs: rc = %d\n", lod2obd(d)->obd_name, rc);
117
118         if (!rc) {
119                 rc = lod_statfs_check(ltd, tgt);
120                 if (rc == -ENOSPC)
121                         return rc;
122         }
123
124         if (reserve &&
125             (reserve + (info.os_reserved_mb_low << 20) >
126              tgt->ltd_statfs.os_bavail * tgt->ltd_statfs.os_bsize))
127                 return -ENOSPC;
128
129         /* check whether device has changed state (active, inactive) */
130         if (rc != 0 && tgt->ltd_active) {
131                 /* turned inactive? */
132                 spin_lock(&d->lod_lock);
133                 if (tgt->ltd_active) {
134                         tgt->ltd_active = 0;
135                         if (rc == -ENOTCONN)
136                                 tgt->ltd_connecting = 1;
137
138                         LASSERT(desc->ld_active_tgt_count > 0);
139                         desc->ld_active_tgt_count--;
140                         set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_flags);
141                         set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_rr.lqr_flags);
142                         CDEBUG(D_CONFIG, "%s: turns inactive\n",
143                                tgt->ltd_exp->exp_obd->obd_name);
144                 }
145                 spin_unlock(&d->lod_lock);
146         } else if (rc == 0 && tgt->ltd_active == 0) {
147                 /* turned active? */
148                 LASSERTF(desc->ld_active_tgt_count < desc->ld_tgt_count,
149                          "active tgt count %d, tgt nr %d\n",
150                          desc->ld_active_tgt_count, desc->ld_tgt_count);
151                 spin_lock(&d->lod_lock);
152                 if (tgt->ltd_active == 0) {
153                         tgt->ltd_active = 1;
154                         tgt->ltd_connecting = 0;
155                         desc->ld_active_tgt_count++;
156                         set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_flags);
157                         set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_rr.lqr_flags);
158                         CDEBUG(D_CONFIG, "%s: turns active\n",
159                                tgt->ltd_exp->exp_obd->obd_name);
160                 }
161                 spin_unlock(&d->lod_lock);
162         }
163         if (rc == -ENOTCONN) {
164                 /* In case that the ENOTCONN for inactive OST state is
165                  * mistreated as MDT disconnection state by the client,
166                  * this error should be changed to someone else.
167                  */
168                 rc = -EREMOTEIO;
169         }
170
171         RETURN(rc);
172 }
173
174 static int lod_is_tgt_usable(struct lu_tgt_descs *ltd, struct lu_tgt_desc *tgt)
175 {
176         int rc;
177
178         rc = lod_statfs_check(ltd, tgt);
179         if (rc)
180                 return rc;
181
182         if (!tgt->ltd_active)
183                 return -ENOTCONN;
184
185         return 0;
186 }
187
188 /**
189  * Maintain per-target statfs data.
190  *
191  * The function refreshes statfs data for all the targets every N seconds.
192  * The actual N is controlled via procfs and set to LOV_DESC_QOS_MAXAGE_DEFAULT
193  * initially.
194  *
195  * \param[in] env       execution environment for this thread
196  * \param[in] lod       LOD device
197  * \param[in] ltd       tgt table
198  */
199 void lod_qos_statfs_update(const struct lu_env *env, struct lod_device *lod,
200                            struct lu_tgt_descs *ltd)
201 {
202         struct obd_device *obd = lod2obd(lod);
203         struct lu_tgt_desc *tgt;
204         time64_t max_age;
205         u64 avail;
206         ENTRY;
207
208         max_age = ktime_get_seconds() - 2 * ltd->ltd_lov_desc.ld_qos_maxage;
209
210         if (obd->obd_osfs_age > max_age)
211                 /* statfs data are quite recent, don't need to refresh it */
212                 RETURN_EXIT;
213
214         down_write(&ltd->ltd_qos.lq_rw_sem);
215
216         if (obd->obd_osfs_age > max_age)
217                 goto out;
218
219         ltd_foreach_tgt(ltd, tgt) {
220                 avail = tgt->ltd_statfs.os_bavail;
221                 if (lod_statfs_and_check(env, lod, ltd, tgt, 0))
222                         continue;
223
224                 if (tgt->ltd_statfs.os_bavail != avail)
225                         /* recalculate weigths */
226                         set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_flags);
227         }
228         obd->obd_osfs_age = ktime_get_seconds();
229
230 out:
231         up_write(&ltd->ltd_qos.lq_rw_sem);
232         EXIT;
233 }
234
235 #define LOV_QOS_EMPTY ((__u32)-1)
236
237 /**
238  * Calculate optimal round-robin order with regard to OSSes.
239  *
240  * Place all the OSTs from pool \a src_pool in a special array to be used for
241  * round-robin (RR) stripe allocation.  The placement algorithm interleaves
242  * OSTs from the different OSSs so that RR allocation can balance OSSs evenly.
243  * Resorts the targets when the number of active targets changes (because of
244  * a new target or activation/deactivation).
245  *
246  * \param[in] lod       LOD device
247  * \param[in] ltd       tgt table
248  * \param[in] src_pool  tgt pool
249  * \param[in] lqr       round-robin list
250  *
251  * \retval 0            on success
252  * \retval -ENOMEM      fails to allocate the array
253  */
254 static int lod_qos_calc_rr(struct lod_device *lod, struct lu_tgt_descs *ltd,
255                            const struct lu_tgt_pool *src_pool,
256                            struct lu_qos_rr *lqr)
257 {
258         struct lu_svr_qos  *svr;
259         struct lu_tgt_desc *tgt;
260         unsigned placed, real_count;
261         unsigned int i;
262         int rc;
263         ENTRY;
264
265         if (!test_bit(LQ_DIRTY, &lqr->lqr_flags)) {
266                 LASSERT(lqr->lqr_pool.op_size);
267                 RETURN(0);
268         }
269
270         /* Do actual allocation. */
271         down_write(&ltd->ltd_qos.lq_rw_sem);
272
273         /*
274          * Check again. While we were sleeping on @lq_rw_sem something could
275          * change.
276          */
277         if (!test_bit(LQ_DIRTY, &lqr->lqr_flags)) {
278                 LASSERT(lqr->lqr_pool.op_size);
279                 up_write(&ltd->ltd_qos.lq_rw_sem);
280                 RETURN(0);
281         }
282
283         real_count = src_pool->op_count;
284
285         /* Zero the pool array */
286         /* alloc_rr is holding a read lock on the pool, so nobody is adding/
287            deleting from the pool. The lq_rw_sem insures that nobody else
288            is reading. */
289         lqr->lqr_pool.op_count = real_count;
290         rc = tgt_pool_extend(&lqr->lqr_pool, real_count);
291         if (rc) {
292                 up_write(&ltd->ltd_qos.lq_rw_sem);
293                 RETURN(rc);
294         }
295         for (i = 0; i < lqr->lqr_pool.op_count; i++)
296                 lqr->lqr_pool.op_array[i] = LOV_QOS_EMPTY;
297
298         /* Place all the tgts from 1 svr at the same time. */
299         placed = 0;
300         list_for_each_entry(svr, &ltd->ltd_qos.lq_svr_list, lsq_svr_list) {
301                 int j = 0;
302
303                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
304                         int next;
305
306                         if (!test_bit(src_pool->op_array[i],
307                                       ltd->ltd_tgt_bitmap))
308                                 continue;
309
310                         tgt = LTD_TGT(ltd, src_pool->op_array[i]);
311                         LASSERT(tgt && tgt->ltd_tgt);
312                         if (tgt->ltd_qos.ltq_svr != svr)
313                                 continue;
314
315                         /* Evenly space these tgts across arrayspace */
316                         next = j * lqr->lqr_pool.op_count / svr->lsq_tgt_count;
317                         while (lqr->lqr_pool.op_array[next] != LOV_QOS_EMPTY)
318                                 next = (next + 1) % lqr->lqr_pool.op_count;
319
320                         lqr->lqr_pool.op_array[next] = src_pool->op_array[i];
321                         j++;
322                         placed++;
323                 }
324         }
325
326         clear_bit(LQ_DIRTY, &lqr->lqr_flags);
327         up_write(&ltd->ltd_qos.lq_rw_sem);
328
329         if (placed != real_count) {
330                 /* This should never happen */
331                 LCONSOLE_ERROR_MSG(0x14e, "Failed to place all tgts in the "
332                                    "round-robin list (%d of %d).\n",
333                                    placed, real_count);
334                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
335                         LCONSOLE(D_WARNING, "rr #%d tgt idx=%d\n", i,
336                                  lqr->lqr_pool.op_array[i]);
337                 }
338                 set_bit(LQ_DIRTY, &lqr->lqr_flags);
339                 RETURN(-EAGAIN);
340         }
341
342 #if 0
343         for (i = 0; i < lqr->lqr_pool.op_count; i++)
344                 QOS_CONSOLE("rr #%d ost idx=%d\n", i, lqr->lqr_pool.op_array[i]);
345 #endif
346
347         RETURN(0);
348 }
349
350 /**
351  * Instantiate and declare creation of a new object.
352  *
353  * The function instantiates LU representation for a new object on the
354  * specified device. Also it declares an intention to create that
355  * object on the storage target.
356  *
357  * Note lu_object_anon() is used which is a trick with regard to LU/OSD
358  * infrastructure - in the existing precreation framework we can't assign FID
359  * at this moment, we do this later once a transaction is started. So the
360  * special method instantiates FID-less object in the cache and later it
361  * will get a FID and proper placement in LU cache.
362  *
363  * \param[in] env       execution environment for this thread
364  * \param[in] d         LOD device
365  * \param[in] ost_idx   OST target index where the object is being created
366  * \param[in] th        transaction handle
367  *
368  * \retval              object ptr on success, ERR_PTR() otherwise
369  */
370 static struct dt_object *lod_qos_declare_object_on(const struct lu_env *env,
371                                                    struct lod_device *d,
372                                                    __u32 ost_idx,
373                                                    bool can_block,
374                                                    struct thandle *th)
375 {
376         struct dt_allocation_hint *ah = &lod_env_info(env)->lti_ah;
377         struct lod_tgt_desc *ost;
378         struct lu_object *o, *n;
379         struct lu_device *nd;
380         struct dt_object *dt;
381         int               rc;
382         ENTRY;
383
384         LASSERT(d);
385         LASSERT(ost_idx < d->lod_ost_descs.ltd_tgts_size);
386         ost = OST_TGT(d,ost_idx);
387         LASSERT(ost);
388         LASSERT(ost->ltd_tgt);
389
390         nd = &ost->ltd_tgt->dd_lu_dev;
391
392         /*
393          * allocate anonymous object with zero fid, real fid
394          * will be assigned by OSP within transaction
395          * XXX: to be fixed with fully-functional OST fids
396          */
397         o = lu_object_anon(env, nd, NULL);
398         if (IS_ERR(o))
399                 GOTO(out, dt = ERR_CAST(o));
400
401         n = lu_object_locate(o->lo_header, nd->ld_type);
402         if (unlikely(n == NULL)) {
403                 CERROR("can't find slice\n");
404                 lu_object_put(env, o);
405                 GOTO(out, dt = ERR_PTR(-EINVAL));
406         }
407
408         dt = container_of(n, struct dt_object, do_lu);
409
410         ah->dah_can_block = can_block;
411         rc = lod_sub_declare_create(env, dt, NULL, ah, NULL, th);
412         if (rc < 0) {
413                 CDEBUG(D_OTHER, "can't declare creation on #%u: %d\n",
414                        ost_idx, rc);
415                 lu_object_put(env, o);
416                 dt = ERR_PTR(rc);
417         }
418
419 out:
420         RETURN(dt);
421 }
422
423 /**
424  * Calculate a minimum acceptable stripe count.
425  *
426  * Return an acceptable stripe count depending on flag LOV_USES_DEFAULT_STRIPE:
427  * all stripes or 3/4 of stripes.
428  *
429  * \param[in] stripe_count      number of stripes requested
430  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
431  *
432  * \retval                      acceptable stripecount
433  */
434 static int min_stripe_count(__u32 stripe_count, int flags)
435 {
436         return (flags & LOV_USES_DEFAULT_STRIPE ?
437                 stripe_count - (stripe_count / 4) : stripe_count);
438 }
439
440 #define LOV_CREATE_RESEED_MULT 30
441 #define LOV_CREATE_RESEED_MIN  2000
442
443 /**
444  * Initialize temporary tgt-in-use array.
445  *
446  * Allocate or extend the array used to mark targets already assigned to a new
447  * striping so they are not used more than once.
448  *
449  * \param[in] env       execution environment for this thread
450  * \param[in] stripes   number of items needed in the array
451  *
452  * \retval 0            on success
453  * \retval -ENOMEM      on error
454  */
455 static inline int lod_qos_tgt_in_use_clear(const struct lu_env *env,
456                                            __u32 stripes)
457 {
458         struct lod_thread_info *info = lod_env_info(env);
459
460         if (info->lti_ea_store_size < sizeof(int) * stripes)
461                 lod_ea_store_resize(info, stripes * sizeof(int));
462         if (info->lti_ea_store_size < sizeof(int) * stripes) {
463                 CERROR("can't allocate memory for tgt-in-use array\n");
464                 return -ENOMEM;
465         }
466         memset(info->lti_ea_store, -1, sizeof(int) * stripes);
467         return 0;
468 }
469
470 /**
471  * Remember a target in the array of used targets.
472  *
473  * Mark the given target as used for a new striping being created. The status
474  * of an tgt in a striping can be checked with lod_qos_is_tgt_used().
475  *
476  * \param[in] env       execution environment for this thread
477  * \param[in] idx       index in the array
478  * \param[in] tgt_idx   target index to mark as used
479  */
480 static inline void lod_qos_tgt_in_use(const struct lu_env *env,
481                                       int idx, int tgt_idx)
482 {
483         struct lod_thread_info *info = lod_env_info(env);
484         int *tgts = info->lti_ea_store;
485
486         LASSERT(info->lti_ea_store_size >= idx * sizeof(int));
487         tgts[idx] = tgt_idx;
488 }
489
490 /**
491  * Check is tgt used in a striping.
492  *
493  * Checks whether tgt with the given index is marked as used in the temporary
494  * array (see lod_qos_tgt_in_use()).
495  *
496  * \param[in] env       execution environment for this thread
497  * \param[in] tgt_idx   target index to check
498  * \param[in] stripes   the number of items used in the array already
499  *
500  * \retval 0            not used
501  * \retval 1            used
502  */
503 static int lod_qos_is_tgt_used(const struct lu_env *env, int tgt_idx,
504                                __u32 stripes)
505 {
506         struct lod_thread_info *info = lod_env_info(env);
507         int *tgts = info->lti_ea_store;
508         __u32 j;
509
510         for (j = 0; j < stripes; j++) {
511                 if (tgts[j] == tgt_idx)
512                         return 1;
513         }
514         return 0;
515 }
516
517 static inline bool
518 lod_obj_is_ost_use_skip_cb(const struct lu_env *env, struct lod_object *lo,
519                            int comp_idx, struct lod_obj_stripe_cb_data *data)
520 {
521         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
522
523         return comp->llc_ost_indices == NULL;
524 }
525
526 static inline int
527 lod_obj_is_ost_use_cb(const struct lu_env *env, struct lod_object *lo,
528                       int comp_idx, struct lod_obj_stripe_cb_data *data)
529 {
530         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
531         int i;
532
533         for (i = 0; i < comp->llc_stripe_count; i++) {
534                 if (comp->llc_ost_indices[i] == data->locd_ost_index) {
535                         data->locd_ost_index = -1;
536                         return -EEXIST;
537                 }
538         }
539
540         return 0;
541 }
542
543 /**
544  * Check is OST used in a composite layout
545  *
546  * \param[in] lo        lod object
547  * \param[in] ost       OST target index to check
548  *
549  * \retval false        not used
550  * \retval true         used
551  */
552 static inline bool lod_comp_is_ost_used(const struct lu_env *env,
553                                        struct lod_object *lo, int ost)
554 {
555         struct lod_obj_stripe_cb_data data = { { 0 } };
556
557         data.locd_ost_index = ost;
558         data.locd_comp_skip_cb = lod_obj_is_ost_use_skip_cb;
559         data.locd_comp_cb = lod_obj_is_ost_use_cb;
560
561         (void)lod_obj_for_each_stripe(env, lo, NULL, &data);
562
563         return data.locd_ost_index == -1;
564 }
565
566 static inline void lod_avoid_update(struct lod_object *lo,
567                                     struct lod_avoid_guide *lag)
568 {
569         if (!lod_is_flr(lo))
570                 return;
571
572         lag->lag_ost_avail--;
573 }
574
575 static inline bool lod_should_avoid_ost(struct lod_object *lo,
576                                         struct lod_avoid_guide *lag,
577                                         __u32 index)
578 {
579         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
580         struct lod_tgt_desc *ost = OST_TGT(lod, index);
581         struct lu_svr_qos *lsq = ost->ltd_qos.ltq_svr;
582         bool used = false;
583         int i;
584
585         if (!test_bit(index, lod->lod_ost_bitmap)) {
586                 QOS_DEBUG("OST%d: been used in conflicting mirror component\n",
587                           index);
588                 return true;
589         }
590
591         /**
592          * we've tried our best, all available OSTs have been used in
593          * overlapped components in the other mirror
594          */
595         if (lag->lag_ost_avail == 0)
596                 return false;
597
598         /* check OSS use */
599         for (i = 0; i < lag->lag_oaa_count; i++) {
600                 if (lag->lag_oss_avoid_array[i] == lsq->lsq_id) {
601                         used = true;
602                         break;
603                 }
604         }
605         /**
606          * if the OSS which OST[index] resides has not been used, we'd like to
607          * use it
608          */
609         if (!used)
610                 return false;
611
612         /* if the OSS has been used, check whether the OST has been used */
613         if (!test_bit(index, lag->lag_ost_avoid_bitmap))
614                 used = false;
615         else
616                 QOS_DEBUG("OST%d: been used in conflicting mirror component\n",
617                           index);
618         return used;
619 }
620
621 static int lod_check_and_reserve_ost(const struct lu_env *env,
622                                      struct lod_object *lo,
623                                      struct lod_layout_component *lod_comp,
624                                      __u32 ost_idx, __u32 speed, __u32 *s_idx,
625                                      struct dt_object **stripe,
626                                      __u32 *ost_indices,
627                                      struct thandle *th,
628                                      bool *overstriped,
629                                      __u64 reserve)
630 {
631         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
632         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
633         struct lu_tgt_desc *ost = OST_TGT(lod, ost_idx);
634         struct dt_object   *o;
635         __u32 stripe_idx = *s_idx;
636         int rc;
637
638         ENTRY;
639
640         rc = lod_statfs_and_check(env, lod, &lod->lod_ost_descs, ost, reserve);
641         if (rc)
642                 RETURN(rc);
643
644         /*
645          * We expect number of precreated objects in f_ffree at
646          * the first iteration, skip OSPs with no objects ready
647          */
648         if (ost->ltd_statfs.os_fprecreated == 0 && speed == 0) {
649                 QOS_DEBUG("#%d: precreation is empty\n", ost_idx);
650                 RETURN(rc);
651         }
652
653         /*
654          * try to use another OSP if this one is degraded
655          */
656         if (ost->ltd_statfs.os_state & OS_STATFS_DEGRADED && speed < 2) {
657                 QOS_DEBUG("#%d: degraded\n", ost_idx);
658                 RETURN(rc);
659         }
660
661         /*
662          * try not allocate on OST which has been used by other
663          * component
664          */
665         if (speed == 0 && lod_comp_is_ost_used(env, lo, ost_idx)) {
666                 QOS_DEBUG("iter %d: OST%d used by other component\n",
667                           speed, ost_idx);
668                 RETURN(rc);
669         }
670
671         /**
672          * try not allocate OSTs used by conflicting component of other mirrors
673          * for the first and second time.
674          */
675         if (speed < 2 && lod_should_avoid_ost(lo, lag, ost_idx)) {
676                 QOS_DEBUG("iter %d: OST%d used by conflicting mirror component\n",
677                           speed, ost_idx);
678                 RETURN(rc);
679         }
680
681         /* do not put >1 objects on a single OST, except for overstriping */
682         if (lod_qos_is_tgt_used(env, ost_idx, stripe_idx)) {
683                 if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
684                         *overstriped = true;
685                 else
686                         RETURN(rc);
687         }
688
689         o = lod_qos_declare_object_on(env, lod, ost_idx, true, th);
690         if (IS_ERR(o)) {
691                 CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
692                        ost_idx, (int) PTR_ERR(o));
693                 rc = PTR_ERR(o);
694                 RETURN(rc);
695         }
696
697         /*
698          * We've successfully declared (reserved) an object
699          */
700         lod_avoid_update(lo, lag);
701         lod_qos_tgt_in_use(env, stripe_idx, ost_idx);
702         stripe[stripe_idx] = o;
703         ost_indices[stripe_idx] = ost_idx;
704         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_LOV_CREATE_RACE, 2);
705         stripe_idx++;
706         *s_idx = stripe_idx;
707
708         RETURN(rc);
709 }
710
711 /**
712  * Allocate a striping using round-robin algorithm.
713  *
714  * Allocates a new striping using round-robin algorithm. The function refreshes
715  * all the internal structures (statfs cache, array of available OSTs sorted
716  * with regard to OSS, etc). The number of stripes required is taken from the
717  * object (must be prepared by the caller), but can change if the flag
718  * LOV_USES_DEFAULT_STRIPE is supplied. The caller should ensure nobody else
719  * is trying to create a striping on the object in parallel. All the internal
720  * structures (like pools, etc) are protected and no additional locking is
721  * required. The function succeeds even if a single stripe is allocated. To save
722  * time we give priority to targets which already have objects precreated.
723  * Full OSTs are skipped (see lod_qos_dev_is_full() for the details).
724  *
725  * \param[in] env               execution environment for this thread
726  * \param[in] lo                LOD object
727  * \param[out] stripe           striping created
728  * \param[out] ost_indices      ost indices of striping created
729  * \param[in] flags             allocation flags (0 or LOV_USES_DEFAULT_STRIPE)
730  * \param[in] th                transaction handle
731  * \param[in] comp_idx          index of ldo_comp_entries
732  *
733  * \retval 0            on success
734  * \retval -ENOSPC      if not enough OSTs are found
735  * \retval negative     negated errno for other failures
736  */
737 static int lod_ost_alloc_rr(const struct lu_env *env, struct lod_object *lo,
738                             struct dt_object **stripe, __u32 *ost_indices,
739                             int flags, struct thandle *th, int comp_idx,
740                             __u64 reserve)
741 {
742         struct lod_layout_component *lod_comp;
743         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
744         struct pool_desc  *pool = NULL;
745         struct lu_tgt_pool *osts;
746         struct lu_qos_rr *lqr;
747         unsigned int i, array_idx;
748         __u32 ost_start_idx_temp;
749         __u32 stripe_idx = 0;
750         __u32 stripe_count, stripe_count_min, ost_idx;
751         int rc, speed = 0, ost_connecting = 0;
752         int stripes_per_ost = 1;
753         bool overstriped = false;
754         ENTRY;
755
756         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
757         lod_comp = &lo->ldo_comp_entries[comp_idx];
758         stripe_count = lod_comp->llc_stripe_count;
759         stripe_count_min = min_stripe_count(stripe_count, flags);
760
761         if (lod_comp->llc_pool != NULL)
762                 pool = lod_find_pool(m, lod_comp->llc_pool);
763
764         if (pool != NULL) {
765                 down_read(&pool_tgt_rw_sem(pool));
766                 osts = &(pool->pool_obds);
767                 lqr = &(pool->pool_rr);
768         } else {
769                 osts = &m->lod_ost_descs.ltd_tgt_pool;
770                 lqr = &(m->lod_ost_descs.ltd_qos.lq_rr);
771         }
772
773         rc = lod_qos_calc_rr(m, &m->lod_ost_descs, osts, lqr);
774         if (rc)
775                 GOTO(out, rc);
776
777         rc = lod_qos_tgt_in_use_clear(env, stripe_count);
778         if (rc)
779                 GOTO(out, rc);
780
781         down_read(&m->lod_ost_descs.ltd_qos.lq_rw_sem);
782         spin_lock(&lqr->lqr_alloc);
783         if (--lqr->lqr_start_count <= 0) {
784                 lqr->lqr_start_idx = prandom_u32_max(osts->op_count);
785                 lqr->lqr_start_count =
786                         (LOV_CREATE_RESEED_MIN / max(osts->op_count, 1U) +
787                          LOV_CREATE_RESEED_MULT) * max(osts->op_count, 1U);
788         } else if (stripe_count_min >= osts->op_count ||
789                         lqr->lqr_start_idx > osts->op_count) {
790                 /* If we have allocated from all of the OSTs, slowly
791                  * precess the next start if the OST/stripe count isn't
792                  * already doing this for us. */
793                 lqr->lqr_start_idx %= osts->op_count;
794                 if (stripe_count > 1 && (osts->op_count % stripe_count) != 1)
795                         ++lqr->lqr_offset_idx;
796         }
797         ost_start_idx_temp = lqr->lqr_start_idx;
798
799 repeat_find:
800
801         QOS_DEBUG("pool '%s' want %d start_idx %d start_count %d offset %d "
802                   "active %d count %d\n",
803                   lod_comp->llc_pool ? lod_comp->llc_pool : "",
804                   stripe_count, lqr->lqr_start_idx, lqr->lqr_start_count,
805                   lqr->lqr_offset_idx, osts->op_count, osts->op_count);
806
807         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
808                 stripes_per_ost =
809                         (lod_comp->llc_stripe_count - 1)/osts->op_count + 1;
810
811         for (i = 0; i < osts->op_count * stripes_per_ost
812              && stripe_idx < stripe_count; i++) {
813                 array_idx = (lqr->lqr_start_idx + lqr->lqr_offset_idx) %
814                                 osts->op_count;
815                 ++lqr->lqr_start_idx;
816                 ost_idx = lqr->lqr_pool.op_array[array_idx];
817
818                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
819                           i, lqr->lqr_start_idx, /* XXX: active*/ 0,
820                           stripe_idx, array_idx, ost_idx);
821
822                 if ((ost_idx == LOV_QOS_EMPTY) ||
823                     !test_bit(ost_idx, m->lod_ost_bitmap))
824                         continue;
825
826                 /* Fail Check before osc_precreate() is called
827                    so we can only 'fail' single OSC. */
828                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
829                         continue;
830
831                 spin_unlock(&lqr->lqr_alloc);
832                 rc = lod_check_and_reserve_ost(env, lo, lod_comp, ost_idx,
833                                                speed, &stripe_idx, stripe,
834                                                ost_indices, th, &overstriped,
835                                                reserve);
836                 spin_lock(&lqr->lqr_alloc);
837
838                 if (rc != 0 && OST_TGT(m, ost_idx)->ltd_connecting)
839                         ost_connecting = 1;
840         }
841         if ((speed < 2) && (stripe_idx < stripe_count_min)) {
842                 /* Try again, allowing slower OSCs */
843                 speed++;
844                 lqr->lqr_start_idx = ost_start_idx_temp;
845
846                 ost_connecting = 0;
847                 goto repeat_find;
848         }
849
850         spin_unlock(&lqr->lqr_alloc);
851         up_read(&m->lod_ost_descs.ltd_qos.lq_rw_sem);
852
853         /* If there are enough OSTs, a component with overstriping requested
854          * will not actually end up overstriped.  The comp should reflect this.
855          */
856         if (!overstriped)
857                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
858
859         if (stripe_idx) {
860                 lod_comp->llc_stripe_count = stripe_idx;
861                 /* at least one stripe is allocated */
862                 rc = 0;
863         } else {
864                 /* nobody provided us with a single object */
865                 if (ost_connecting)
866                         rc = -EINPROGRESS;
867                 else
868                         rc = -ENOSPC;
869         }
870
871 out:
872         if (pool != NULL) {
873                 up_read(&pool_tgt_rw_sem(pool));
874                 /* put back ref got by lod_find_pool() */
875                 lod_pool_putref(pool);
876         }
877
878         RETURN(rc);
879 }
880
881 static int
882 lod_qos_mdt_in_use_init(const struct lu_env *env,
883                         const struct lu_tgt_descs *ltd,
884                         u32 stripe_idx, u32 stripe_count,
885                         const struct lu_tgt_pool *pool,
886                         struct dt_object **stripes)
887 {
888         u32 mdt_idx;
889         struct lu_tgt_desc *mdt;
890         int i, j;
891         int rc;
892
893         rc = lod_qos_tgt_in_use_clear(env, stripe_count);
894         if (rc)
895                 return rc;
896
897         /* if stripe_idx > 1, we are splitting directory, mark existing stripes
898          * in_use. Because for either split or creation, stripe 0 is local,
899          * don't mark it in use.
900          */
901         for (i = 1; i < stripe_idx; i++) {
902                 LASSERT(stripes[i]);
903                 for (j = 0; j < pool->op_count; j++) {
904                         mdt_idx = pool->op_array[j];
905
906                         if (!test_bit(mdt_idx, ltd->ltd_tgt_bitmap))
907                                 continue;
908
909                         mdt = LTD_TGT(ltd, mdt_idx);
910                         if (&mdt->ltd_tgt->dd_lu_dev ==
911                             stripes[i]->do_lu.lo_dev)
912                                 lod_qos_tgt_in_use(env, i, mdt_idx);
913                 }
914         }
915
916         return 0;
917 }
918
919 /**
920  * Allocate a striping using round-robin algorithm.
921  *
922  * Allocates a new striping using round-robin algorithm. The function refreshes
923  * all the internal structures (statfs cache, array of available remote MDTs
924  * sorted with regard to MDS, etc). The number of stripes required is taken from
925  * the object (must be prepared by the caller). The caller should ensure nobody
926  * else is trying to create a striping on the object in parallel. All the
927  * internal structures (like pools, etc) are protected and no additional locking
928  * is required. The function succeeds even if a single stripe is allocated.
929  *
930  * \param[in] env               execution environment for this thread
931  * \param[in] lo                LOD object
932  * \param[out] stripes          striping created
933  *
934  * \retval positive     stripe objects allocated, including the first stripe
935  *                      allocated outside
936  * \retval -ENOSPC      if not enough MDTs are found
937  * \retval negative     negated errno for other failures
938  */
939 int lod_mdt_alloc_rr(const struct lu_env *env, struct lod_object *lo,
940                      struct dt_object **stripes, u32 stripe_idx,
941                      u32 stripe_count)
942 {
943         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
944         struct lu_tgt_descs *ltd = &lod->lod_mdt_descs;
945         struct lu_tgt_pool *pool;
946         struct lu_qos_rr *lqr;
947         struct lu_tgt_desc *mdt;
948         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
949         struct lu_fid fid = { 0 };
950         struct dt_object *dto;
951         unsigned int pool_idx;
952         unsigned int i;
953         u32 saved_idx = stripe_idx;
954         u32 start_mdt;
955         u32 mdt_idx;
956         bool use_degraded = false;
957         int tgt_connecting = 0;
958         int rc;
959
960         ENTRY;
961
962         pool = &ltd->ltd_tgt_pool;
963         lqr = &ltd->ltd_qos.lq_rr;
964         rc = lod_qos_calc_rr(lod, ltd, pool, lqr);
965         if (rc)
966                 RETURN(rc);
967
968         rc = lod_qos_mdt_in_use_init(env, ltd, stripe_idx, stripe_count, pool,
969                                      stripes);
970         if (rc)
971                 RETURN(rc);
972
973         down_read(&ltd->ltd_qos.lq_rw_sem);
974         spin_lock(&lqr->lqr_alloc);
975         if (--lqr->lqr_start_count <= 0) {
976                 lqr->lqr_start_idx = prandom_u32_max(pool->op_count);
977                 lqr->lqr_start_count =
978                         (LOV_CREATE_RESEED_MIN / max(pool->op_count, 1U) +
979                          LOV_CREATE_RESEED_MULT) * max(pool->op_count, 1U);
980         } else if (stripe_count - 1 >= pool->op_count ||
981                    lqr->lqr_start_idx > pool->op_count) {
982                 /* If we have allocated from all of the tgts, slowly
983                  * precess the next start if the tgt/stripe count isn't
984                  * already doing this for us. */
985                 lqr->lqr_start_idx %= pool->op_count;
986                 if (stripe_count - 1 > 1 &&
987                     (pool->op_count % (stripe_count - 1)) != 1)
988                         ++lqr->lqr_offset_idx;
989         }
990         start_mdt = lqr->lqr_start_idx;
991
992 repeat_find:
993         QOS_DEBUG("want=%d start_idx=%d start_count=%d offset=%d active=%d count=%d\n",
994                   stripe_count - 1, lqr->lqr_start_idx, lqr->lqr_start_count,
995                   lqr->lqr_offset_idx, pool->op_count, pool->op_count);
996
997         for (i = 0; i < pool->op_count && stripe_idx < stripe_count; i++) {
998                 pool_idx = (lqr->lqr_start_idx + lqr->lqr_offset_idx) %
999                             pool->op_count;
1000                 ++lqr->lqr_start_idx;
1001                 mdt_idx = lqr->lqr_pool.op_array[pool_idx];
1002                 mdt = LTD_TGT(ltd, mdt_idx);
1003
1004                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
1005                           i, lqr->lqr_start_idx, /* XXX: active*/ 0,
1006                           stripe_idx, pool_idx, mdt_idx);
1007
1008                 if (mdt_idx == LOV_QOS_EMPTY ||
1009                     !test_bit(mdt_idx, ltd->ltd_tgt_bitmap))
1010                         continue;
1011
1012                 /* do not put >1 objects on one MDT */
1013                 if (lod_qos_is_tgt_used(env, mdt_idx, stripe_idx))
1014                         continue;
1015
1016                 rc = lod_is_tgt_usable(ltd, mdt);
1017                 if (rc) {
1018                         if (mdt->ltd_connecting)
1019                                 tgt_connecting = 1;
1020                         continue;
1021                 }
1022
1023                 /* try to use another OSP if this one is degraded */
1024                 if (mdt->ltd_statfs.os_state & OS_STATFS_DEGRADED &&
1025                     !use_degraded) {
1026                         QOS_DEBUG("#%d: degraded\n", mdt_idx);
1027                         continue;
1028                 }
1029                 spin_unlock(&lqr->lqr_alloc);
1030
1031                 rc = dt_fid_alloc(env, mdt->ltd_tgt, &fid, NULL, NULL);
1032                 if (rc < 0) {
1033                         QOS_DEBUG("#%d: alloc FID failed: %dl\n", mdt_idx, rc);
1034                         spin_lock(&lqr->lqr_alloc);
1035                         continue;
1036                 }
1037
1038                 dto = dt_locate_at(env, mdt->ltd_tgt, &fid,
1039                                 lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
1040                                 &conf);
1041
1042                 spin_lock(&lqr->lqr_alloc);
1043                 if (IS_ERR(dto)) {
1044                         QOS_DEBUG("can't alloc stripe on #%u: %d\n",
1045                                   mdt->ltd_index, (int) PTR_ERR(dto));
1046
1047                         if (mdt->ltd_connecting)
1048                                 tgt_connecting = 1;
1049                         continue;
1050                 }
1051
1052                 lod_qos_tgt_in_use(env, stripe_idx, mdt_idx);
1053                 stripes[stripe_idx++] = dto;
1054         }
1055
1056         if (!use_degraded && stripe_idx < stripe_count) {
1057                 /* Try again, allowing slower MDTs */
1058                 use_degraded = true;
1059                 lqr->lqr_start_idx = start_mdt;
1060
1061                 tgt_connecting = 0;
1062                 goto repeat_find;
1063         }
1064         spin_unlock(&lqr->lqr_alloc);
1065         up_read(&ltd->ltd_qos.lq_rw_sem);
1066
1067         if (stripe_idx > saved_idx)
1068                 /* at least one stripe is allocated */
1069                 RETURN(stripe_idx);
1070
1071         /* nobody provided us with a single object */
1072         if (tgt_connecting)
1073                 RETURN(-EINPROGRESS);
1074
1075         RETURN(-ENOSPC);
1076 }
1077
1078 /**
1079  * Allocate a specific striping layout on a user defined set of OSTs.
1080  *
1081  * Allocates new striping using the OST index range provided by the data from
1082  * the lmm_obejcts contained in the lov_user_md passed to this method. Full
1083  * OSTs are not considered. The exact order of OSTs requested by the user
1084  * is respected as much as possible depending on OST status. The number of
1085  * stripes needed and stripe offset are taken from the object. If that number
1086  * can not be met, then the function returns a failure and then it's the
1087  * caller's responsibility to release the stripes allocated. All the internal
1088  * structures are protected, but no concurrent allocation is allowed on the
1089  * same objects.
1090  *
1091  * \param[in] env               execution environment for this thread
1092  * \param[in] lo                LOD object
1093  * \param[out] stripe           striping created
1094  * \param[out] ost_indices      ost indices of striping created
1095  * \param[in] th                transaction handle
1096  * \param[in] comp_idx          index of ldo_comp_entries
1097  *
1098  * \retval 0            on success
1099  * \retval -ENODEV      OST index does not exist on file system
1100  * \retval -EINVAL      requested OST index is invalid
1101  * \retval negative     negated errno on error
1102  */
1103 static int lod_alloc_ost_list(const struct lu_env *env, struct lod_object *lo,
1104                               struct dt_object **stripe, __u32 *ost_indices,
1105                               struct thandle *th, int comp_idx, __u64 reserve)
1106 {
1107         struct lod_layout_component *lod_comp;
1108         struct lod_device       *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1109         struct dt_object        *o;
1110         unsigned int            array_idx = 0;
1111         int                     stripe_count = 0;
1112         int                     i;
1113         int                     rc = -EINVAL;
1114         ENTRY;
1115
1116         /* for specific OSTs layout */
1117         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1118         lod_comp = &lo->ldo_comp_entries[comp_idx];
1119         LASSERT(lod_comp->llc_ostlist.op_array);
1120         LASSERT(lod_comp->llc_ostlist.op_count);
1121
1122         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1123         if (rc < 0)
1124                 RETURN(rc);
1125
1126         if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT)
1127                 lod_comp->llc_stripe_offset =
1128                                 lod_comp->llc_ostlist.op_array[0];
1129
1130         for (i = 0; i < lod_comp->llc_stripe_count; i++) {
1131                 if (lod_comp->llc_ostlist.op_array[i] ==
1132                     lod_comp->llc_stripe_offset) {
1133                         array_idx = i;
1134                         break;
1135                 }
1136         }
1137         if (i == lod_comp->llc_stripe_count) {
1138                 CDEBUG(D_OTHER,
1139                        "%s: start index %d not in the specified list of OSTs\n",
1140                        lod2obd(m)->obd_name, lod_comp->llc_stripe_offset);
1141                 RETURN(-EINVAL);
1142         }
1143
1144         for (i = 0; i < lod_comp->llc_stripe_count;
1145              i++, array_idx = (array_idx + 1) % lod_comp->llc_stripe_count) {
1146                 __u32 ost_idx = lod_comp->llc_ostlist.op_array[array_idx];
1147
1148                 if (!test_bit(ost_idx, m->lod_ost_bitmap)) {
1149                         rc = -ENODEV;
1150                         break;
1151                 }
1152
1153                 /* do not put >1 objects on a single OST, except for
1154                  * overstriping
1155                  */
1156                 if (lod_qos_is_tgt_used(env, ost_idx, stripe_count) &&
1157                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)) {
1158                         rc = -EINVAL;
1159                         break;
1160                 }
1161
1162                 rc = lod_statfs_and_check(env, m, &m->lod_ost_descs,
1163                                           LTD_TGT(&m->lod_ost_descs, ost_idx),
1164                                           reserve);
1165                 if (rc < 0) /* this OSP doesn't feel well */
1166                         break;
1167
1168                 o = lod_qos_declare_object_on(env, m, ost_idx, true, th);
1169                 if (IS_ERR(o)) {
1170                         rc = PTR_ERR(o);
1171                         CDEBUG(D_OTHER,
1172                                "%s: can't declare new object on #%u: %d\n",
1173                                lod2obd(m)->obd_name, ost_idx, rc);
1174                         break;
1175                 }
1176
1177                 /*
1178                  * We've successfully declared (reserved) an object
1179                  */
1180                 lod_qos_tgt_in_use(env, stripe_count, ost_idx);
1181                 stripe[stripe_count] = o;
1182                 ost_indices[stripe_count] = ost_idx;
1183                 stripe_count++;
1184         }
1185
1186         RETURN(rc);
1187 }
1188
1189 /**
1190  * Allocate a striping on a predefined set of OSTs.
1191  *
1192  * Allocates new layout starting from OST index in lo->ldo_stripe_offset.
1193  * Full OSTs are not considered. The exact order of OSTs is not important and
1194  * varies depending on OST status. The allocation procedure prefers the targets
1195  * with precreated objects ready. The number of stripes needed and stripe
1196  * offset are taken from the object. If that number cannot be met, then the
1197  * function returns an error and then it's the caller's responsibility to
1198  * release the stripes allocated. All the internal structures are protected,
1199  * but no concurrent allocation is allowed on the same objects.
1200  *
1201  * \param[in] env               execution environment for this thread
1202  * \param[in] lo                LOD object
1203  * \param[out] stripe           striping created
1204  * \param[out] ost_indices      ost indices of striping created
1205  * \param[in] flags             not used
1206  * \param[in] th                transaction handle
1207  * \param[in] comp_idx          index of ldo_comp_entries
1208  *
1209  * \retval 0            on success
1210  * \retval -ENOSPC      if no OST objects are available at all
1211  * \retval -EFBIG       if not enough OST objects are found
1212  * \retval -EINVAL      requested offset is invalid
1213  * \retval negative     errno on failure
1214  */
1215 static int lod_ost_alloc_specific(const struct lu_env *env,
1216                                   struct lod_object *lo,
1217                                   struct dt_object **stripe, __u32 *ost_indices,
1218                                   int flags, struct thandle *th, int comp_idx,
1219                                   __u64 reserve)
1220 {
1221         struct lod_layout_component *lod_comp;
1222         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1223         struct dt_object *o;
1224         struct lu_tgt_desc *tgt;
1225         __u32 ost_idx;
1226         unsigned int i, array_idx, ost_count;
1227         int rc, stripe_num = 0;
1228         int speed = 0;
1229         struct pool_desc *pool = NULL;
1230         struct lu_tgt_pool *osts;
1231         int stripes_per_ost = 1;
1232         bool overstriped = false;
1233         ENTRY;
1234
1235         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1236         lod_comp = &lo->ldo_comp_entries[comp_idx];
1237
1238         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1239         if (rc)
1240                 GOTO(out, rc);
1241
1242         if (lod_comp->llc_pool != NULL)
1243                 pool = lod_find_pool(m, lod_comp->llc_pool);
1244
1245         if (pool != NULL) {
1246                 down_read(&pool_tgt_rw_sem(pool));
1247                 osts = &(pool->pool_obds);
1248         } else {
1249                 osts = &m->lod_ost_descs.ltd_tgt_pool;
1250         }
1251
1252         ost_count = osts->op_count;
1253
1254 repeat_find:
1255         /* search loi_ost_idx in ost array */
1256         array_idx = 0;
1257         for (i = 0; i < ost_count; i++) {
1258                 if (osts->op_array[i] == lod_comp->llc_stripe_offset) {
1259                         array_idx = i;
1260                         break;
1261                 }
1262         }
1263         if (i == ost_count) {
1264                 CERROR("Start index %d not found in pool '%s'\n",
1265                        lod_comp->llc_stripe_offset,
1266                        lod_comp->llc_pool ? lod_comp->llc_pool : "");
1267                 GOTO(out, rc = -EINVAL);
1268         }
1269
1270         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1271                 stripes_per_ost =
1272                         (lod_comp->llc_stripe_count - 1)/ost_count + 1;
1273
1274         for (i = 0; i < ost_count * stripes_per_ost;
1275                         i++, array_idx = (array_idx + 1) % ost_count) {
1276                 ost_idx = osts->op_array[array_idx];
1277
1278                 if (!test_bit(ost_idx, m->lod_ost_bitmap))
1279                         continue;
1280
1281                 /* Fail Check before osc_precreate() is called
1282                    so we can only 'fail' single OSC. */
1283                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1284                         continue;
1285
1286                 /*
1287                  * do not put >1 objects on a single OST, except for
1288                  * overstriping, where it is intended
1289                  */
1290                 if (lod_qos_is_tgt_used(env, ost_idx, stripe_num)) {
1291                         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1292                                 overstriped = true;
1293                         else
1294                                 continue;
1295                 }
1296
1297                 /*
1298                  * try not allocate on the OST used by other component
1299                  */
1300                 if (speed == 0 && i != 0 &&
1301                     lod_comp_is_ost_used(env, lo, ost_idx))
1302                         continue;
1303
1304                 tgt = LTD_TGT(&m->lod_ost_descs, ost_idx);
1305
1306                 /* Drop slow OSCs if we can, but not for requested start idx.
1307                  *
1308                  * This means "if OSC is slow and it is not the requested
1309                  * start OST, then it can be skipped, otherwise skip it only
1310                  * if it is inactive/recovering/out-of-space." */
1311
1312                 rc = lod_statfs_and_check(env, m, &m->lod_ost_descs,
1313                                           tgt, reserve);
1314                 if (rc) {
1315                         /* this OSP doesn't feel well */
1316                         continue;
1317                 }
1318
1319                 /*
1320                  * We expect number of precreated objects at the first
1321                  * iteration.  Skip OSPs with no objects ready.  Don't apply
1322                  * this logic to OST specified with stripe_offset.
1323                  */
1324                 if (i && !tgt->ltd_statfs.os_fprecreated && !speed)
1325                         continue;
1326
1327                 o = lod_qos_declare_object_on(env, m, ost_idx, true, th);
1328                 if (IS_ERR(o)) {
1329                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
1330                                ost_idx, (int) PTR_ERR(o));
1331                         continue;
1332                 }
1333
1334                 /*
1335                  * We've successfully declared (reserved) an object
1336                  */
1337                 lod_qos_tgt_in_use(env, stripe_num, ost_idx);
1338                 stripe[stripe_num] = o;
1339                 ost_indices[stripe_num] = ost_idx;
1340                 stripe_num++;
1341
1342                 /* We have enough stripes */
1343                 if (stripe_num == lod_comp->llc_stripe_count)
1344                         GOTO(out, rc = 0);
1345         }
1346         if (speed < 2) {
1347                 /* Try again, allowing slower OSCs */
1348                 speed++;
1349                 goto repeat_find;
1350         }
1351
1352         /* If we were passed specific striping params, then a failure to
1353          * meet those requirements is an error, since we can't reallocate
1354          * that memory (it might be part of a larger array or something).
1355          */
1356         CERROR("can't lstripe objid "DFID": have %d want %u\n",
1357                PFID(lu_object_fid(lod2lu_obj(lo))), stripe_num,
1358                lod_comp->llc_stripe_count);
1359         rc = stripe_num == 0 ? -ENOSPC : -EFBIG;
1360
1361         /* If there are enough OSTs, a component with overstriping requessted
1362          * will not actually end up overstriped.  The comp should reflect this.
1363          */
1364         if (rc == 0 && !overstriped)
1365                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1366
1367 out:
1368         if (pool != NULL) {
1369                 up_read(&pool_tgt_rw_sem(pool));
1370                 /* put back ref got by lod_find_pool() */
1371                 lod_pool_putref(pool);
1372         }
1373
1374         RETURN(rc);
1375 }
1376
1377 /**
1378  * Allocate a striping using an algorithm with weights.
1379  *
1380  * The function allocates OST objects to create a striping. The algorithm
1381  * used is based on weights (currently only using the free space), and it's
1382  * trying to ensure the space is used evenly by OSTs and OSSs. The striping
1383  * configuration (# of stripes, offset, pool) is taken from the object and
1384  * is prepared by the caller.
1385  *
1386  * If LOV_USES_DEFAULT_STRIPE is not passed and prepared configuration can't
1387  * be met due to too few OSTs, then allocation fails. If the flag is passed
1388  * fewer than 3/4 of the requested number of stripes can be allocated, then
1389  * allocation fails.
1390  *
1391  * No concurrent allocation is allowed on the object and this must be ensured
1392  * by the caller. All the internal structures are protected by the function.
1393  *
1394  * The algorithm has two steps: find available OSTs and calculate their
1395  * weights, then select the OSTs with their weights used as the probability.
1396  * An OST with a higher weight is proportionately more likely to be selected
1397  * than one with a lower weight.
1398  *
1399  * \param[in] env               execution environment for this thread
1400  * \param[in] lo                LOD object
1401  * \param[out] stripe           striping created
1402  * \param[out] ost_indices      ost indices of striping created
1403  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
1404  * \param[in] th                transaction handle
1405  * \param[in] comp_idx          index of ldo_comp_entries
1406  *
1407  * \retval 0            on success
1408  * \retval -EAGAIN      not enough OSTs are found for specified stripe count
1409  * \retval -EINVAL      requested OST index is invalid
1410  * \retval negative     errno on failure
1411  */
1412 static int lod_ost_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1413                              struct dt_object **stripe, __u32 *ost_indices,
1414                              int flags, struct thandle *th, int comp_idx,
1415                              __u64 reserve)
1416 {
1417         struct lod_layout_component *lod_comp;
1418         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1419         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
1420         struct lod_tgt_desc *ost;
1421         struct dt_object *o;
1422         __u64 total_weight = 0;
1423         struct pool_desc *pool = NULL;
1424         struct lu_tgt_pool *osts;
1425         unsigned int i;
1426         __u32 nfound, good_osts, stripe_count, stripe_count_min;
1427         bool overstriped = false;
1428         int stripes_per_ost = 1;
1429         bool slow = false;
1430         int rc = 0;
1431         ENTRY;
1432
1433         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1434         lod_comp = &lo->ldo_comp_entries[comp_idx];
1435         stripe_count = lod_comp->llc_stripe_count;
1436         stripe_count_min = min_stripe_count(stripe_count, flags);
1437         if (stripe_count_min < 1)
1438                 RETURN(-EINVAL);
1439
1440         if (lod_comp->llc_pool != NULL)
1441                 pool = lod_find_pool(lod, lod_comp->llc_pool);
1442
1443         if (pool != NULL) {
1444                 down_read(&pool_tgt_rw_sem(pool));
1445                 osts = &(pool->pool_obds);
1446         } else {
1447                 osts = &lod->lod_ost_descs.ltd_tgt_pool;
1448         }
1449
1450         /* Detect -EAGAIN early, before expensive lock is taken. */
1451         if (!ltd_qos_is_usable(&lod->lod_ost_descs))
1452                 GOTO(out_nolock, rc = -EAGAIN);
1453
1454         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1455                 stripes_per_ost =
1456                         (lod_comp->llc_stripe_count - 1)/osts->op_count + 1;
1457
1458         /* Do actual allocation, use write lock here. */
1459         down_write(&lod->lod_ost_descs.ltd_qos.lq_rw_sem);
1460
1461         /*
1462          * Check again, while we were sleeping on @lq_rw_sem things could
1463          * change.
1464          */
1465         if (!ltd_qos_is_usable(&lod->lod_ost_descs))
1466                 GOTO(out, rc = -EAGAIN);
1467
1468         rc = ltd_qos_penalties_calc(&lod->lod_ost_descs);
1469         if (rc)
1470                 GOTO(out, rc);
1471
1472         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1473         if (rc)
1474                 GOTO(out, rc);
1475
1476         good_osts = 0;
1477         /* Find all the OSTs that are valid stripe candidates */
1478         for (i = 0; i < osts->op_count; i++) {
1479                 if (!test_bit(osts->op_array[i], lod->lod_ost_bitmap))
1480                         continue;
1481
1482                 ost = OST_TGT(lod, osts->op_array[i]);
1483                 ost->ltd_qos.ltq_usable = 0;
1484
1485                 rc = lod_statfs_and_check(env, lod, &lod->lod_ost_descs,
1486                                           ost, reserve);
1487                 if (rc) {
1488                         /* this OSP doesn't feel well */
1489                         continue;
1490                 }
1491
1492                 if (ost->ltd_statfs.os_state & OS_STATFS_DEGRADED)
1493                         continue;
1494
1495                 /* Fail Check before osc_precreate() is called
1496                  * so we can only 'fail' single OSC.
1497                  */
1498                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) &&
1499                                    osts->op_array[i] == 0)
1500                         continue;
1501
1502                 ost->ltd_qos.ltq_usable = 1;
1503                 lu_tgt_qos_weight_calc(ost);
1504                 total_weight += ost->ltd_qos.ltq_weight;
1505
1506                 good_osts++;
1507         }
1508
1509         QOS_DEBUG("found %d good osts\n", good_osts);
1510
1511         if (good_osts < stripe_count_min)
1512                 GOTO(out, rc = -EAGAIN);
1513
1514         /* If we do not have enough OSTs for the requested stripe count, do not
1515          * put more stripes per OST than requested.
1516          */
1517         if (stripe_count / stripes_per_ost > good_osts)
1518                 stripe_count = good_osts * stripes_per_ost;
1519
1520         /* Find enough OSTs with weighted random allocation. */
1521         nfound = 0;
1522         while (nfound < stripe_count) {
1523                 u64 rand, cur_weight;
1524
1525                 cur_weight = 0;
1526                 rc = -ENOSPC;
1527
1528                 rand = lu_prandom_u64_max(total_weight);
1529
1530                 /* On average, this will hit larger-weighted OSTs more often.
1531                  * 0-weight OSTs will always get used last (only when rand=0)
1532                  */
1533                 for (i = 0; i < osts->op_count; i++) {
1534                         __u32 idx = osts->op_array[i];
1535                         struct lod_tgt_desc *ost = OST_TGT(lod, idx);
1536
1537                         if (lod_should_avoid_ost(lo, lag, idx))
1538                                 continue;
1539
1540                         ost = OST_TGT(lod, idx);
1541
1542                         if (!ost->ltd_qos.ltq_usable)
1543                                 continue;
1544
1545                         cur_weight += ost->ltd_qos.ltq_weight;
1546                         QOS_DEBUG("stripe_count=%d nfound=%d cur_weight=%llu "
1547                                   "rand=%llu total_weight=%llu\n",
1548                                   stripe_count, nfound, cur_weight, rand,
1549                                   total_weight);
1550
1551                         if (cur_weight < rand)
1552                                 continue;
1553
1554                         QOS_DEBUG("stripe=%d to idx=%d\n", nfound, idx);
1555                         /*
1556                          * do not put >1 objects on a single OST, except for
1557                          * overstriping
1558                          */
1559                         if ((lod_comp_is_ost_used(env, lo, idx)) &&
1560                             !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
1561                                 continue;
1562
1563                         if (lod_qos_is_tgt_used(env, idx, nfound)) {
1564                                 if (lod_comp->llc_pattern &
1565                                     LOV_PATTERN_OVERSTRIPING)
1566                                         overstriped = true;
1567                                 else
1568                                         continue;
1569                         }
1570
1571                         o = lod_qos_declare_object_on(env, lod, idx, slow, th);
1572                         if (IS_ERR(o)) {
1573                                 QOS_DEBUG("can't declare object on #%u: %d\n",
1574                                           idx, (int) PTR_ERR(o));
1575                                 continue;
1576                         }
1577
1578                         lod_avoid_update(lo, lag);
1579                         lod_qos_tgt_in_use(env, nfound, idx);
1580                         stripe[nfound] = o;
1581                         ost_indices[nfound] = idx;
1582                         ltd_qos_update(&lod->lod_ost_descs, ost, &total_weight);
1583                         nfound++;
1584                         rc = 0;
1585                         break;
1586                 }
1587
1588                 if (rc && !slow && nfound < stripe_count) {
1589                         /* couldn't allocate using precreated objects
1590                          * so try to wait for new precreations */
1591                         slow = true;
1592                         rc = 0;
1593                 }
1594
1595                 if (rc) {
1596                         /* no OST found on this iteration, give up */
1597                         break;
1598                 }
1599         }
1600
1601         if (unlikely(nfound != stripe_count)) {
1602                 /*
1603                  * when the decision to use weighted algorithm was made
1604                  * we had enough appropriate OSPs, but this state can
1605                  * change anytime (no space on OST, broken connection, etc)
1606                  * so it's possible OSP won't be able to provide us with
1607                  * an object due to just changed state
1608                  */
1609                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1610                           lod2obd(lod)->obd_name, stripe_count, nfound);
1611                 for (i = 0; i < nfound; i++) {
1612                         LASSERT(stripe[i] != NULL);
1613                         dt_object_put(env, stripe[i]);
1614                         stripe[i] = NULL;
1615                 }
1616
1617                 /* makes sense to rebalance next time */
1618                 set_bit(LQ_DIRTY, &lod->lod_ost_descs.ltd_qos.lq_flags);
1619                 clear_bit(LQ_SAME_SPACE, &lod->lod_ost_descs.ltd_qos.lq_flags);
1620                 rc = -EAGAIN;
1621         }
1622
1623         /* If there are enough OSTs, a component with overstriping requessted
1624          * will not actually end up overstriped.  The comp should reflect this.
1625          */
1626         if (rc == 0 && !overstriped)
1627                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1628
1629 out:
1630         up_write(&lod->lod_ost_descs.ltd_qos.lq_rw_sem);
1631
1632 out_nolock:
1633         if (pool != NULL) {
1634                 up_read(&pool_tgt_rw_sem(pool));
1635                 /* put back ref got by lod_find_pool() */
1636                 lod_pool_putref(pool);
1637         }
1638
1639         RETURN(rc);
1640 }
1641
1642 /**
1643  * Allocate a striping using an algorithm with weights.
1644  *
1645  * The function allocates remote MDT objects to create a striping, the first
1646  * object was already allocated on current MDT to ensure master object and
1647  * the first object are on the same MDT. The algorithm used is based on weights
1648  * (both free space and inodes), and it's trying to ensure the space/inodes are
1649  * used evenly by MDTs and MDSs. The striping configuration (# of stripes,
1650  * offset, pool) is taken from the object and is prepared by the caller.
1651  *
1652  * If prepared configuration can't be met due to too few MDTs, then allocation
1653  * fails.
1654  *
1655  * No concurrent allocation is allowed on the object and this must be ensured
1656  * by the caller. All the internal structures are protected by the function.
1657  *
1658  * The algorithm has two steps: find available MDTs and calculate their
1659  * weights, then select the MDTs with their weights used as the probability.
1660  * An MDT with a higher weight is proportionately more likely to be selected
1661  * than one with a lower weight.
1662  *
1663  * \param[in] env               execution environment for this thread
1664  * \param[in] lo                LOD object
1665  * \param[in] stripe_idx        starting stripe index to allocate, if it's not
1666  *                              0, we are restriping directory
1667  * \param[in] stripe_count      total stripe count
1668  * \param[out] stripes          striping created
1669  *
1670  * \retval positive     stripes allocated, and it should be equal to
1671  *                      lo->ldo_dir_stripe_count
1672  * \retval -EAGAIN      not enough tgts are found for specified stripe count
1673  * \retval -EINVAL      requested MDT index is invalid
1674  * \retval negative     errno on failure
1675  */
1676 int lod_mdt_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1677                       struct dt_object **stripes, u32 stripe_idx,
1678                       u32 stripe_count)
1679 {
1680         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1681         struct lu_tgt_descs *ltd = &lod->lod_mdt_descs;
1682         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
1683         struct lu_fid fid = { 0 };
1684         const struct lu_tgt_pool *pool;
1685         struct lu_tgt_desc *mdt;
1686         struct dt_object *dto;
1687         u64 total_weight = 0;
1688         u32 saved_idx = stripe_idx;
1689         u32 mdt_idx;
1690         unsigned int good_mdts;
1691         unsigned int i;
1692         int rc = 0;
1693
1694         ENTRY;
1695
1696         LASSERT(stripe_idx <= stripe_count);
1697         if (stripe_idx == stripe_count)
1698                 RETURN(stripe_count);
1699
1700         /* use MDT pool in @ltd, once MDT pool is supported in the future, it
1701          * can be passed in as argument like OST object allocation.
1702          */
1703         pool = &ltd->ltd_tgt_pool;
1704
1705         /* Detect -EAGAIN early, before expensive lock is taken. */
1706         if (!ltd_qos_is_usable(ltd))
1707                 RETURN(-EAGAIN);
1708
1709         rc = lod_qos_mdt_in_use_init(env, ltd, stripe_idx, stripe_count, pool,
1710                                      stripes);
1711         if (rc)
1712                 RETURN(rc);
1713
1714         /* Do actual allocation, use write lock here. */
1715         down_write(&ltd->ltd_qos.lq_rw_sem);
1716
1717         /*
1718          * Check again, while we were sleeping on @lq_rw_sem things could
1719          * change.
1720          */
1721         if (!ltd_qos_is_usable(ltd))
1722                 GOTO(unlock, rc = -EAGAIN);
1723
1724         rc = ltd_qos_penalties_calc(ltd);
1725         if (rc)
1726                 GOTO(unlock, rc);
1727
1728         good_mdts = 0;
1729         /* Find all the MDTs that are valid stripe candidates */
1730         for (i = 0; i < pool->op_count; i++) {
1731                 if (!test_bit(pool->op_array[i], ltd->ltd_tgt_bitmap))
1732                         continue;
1733
1734                 mdt = LTD_TGT(ltd, pool->op_array[i]);
1735                 mdt->ltd_qos.ltq_usable = 0;
1736
1737                 rc = lod_is_tgt_usable(ltd, mdt);
1738                 if (rc)
1739                         continue;
1740
1741                 if (mdt->ltd_statfs.os_state & OS_STATFS_DEGRADED)
1742                         continue;
1743
1744                 mdt->ltd_qos.ltq_usable = 1;
1745                 lu_tgt_qos_weight_calc(mdt);
1746                 total_weight += mdt->ltd_qos.ltq_weight;
1747
1748                 good_mdts++;
1749         }
1750
1751         QOS_DEBUG("found %d good MDTs\n", good_mdts);
1752
1753         if (good_mdts < stripe_count - stripe_idx)
1754                 GOTO(unlock, rc = -EAGAIN);
1755
1756         /* Find enough MDTs with weighted random allocation. */
1757         while (stripe_idx < stripe_count) {
1758                 u64 rand, cur_weight;
1759
1760                 cur_weight = 0;
1761                 rc = -ENOSPC;
1762
1763                 rand = lu_prandom_u64_max(total_weight);
1764
1765                 /* On average, this will hit larger-weighted MDTs more often.
1766                  * 0-weight MDT will always get used last (only when rand=0) */
1767                 for (i = 0; i < pool->op_count; i++) {
1768                         int rc2;
1769
1770                         mdt_idx = pool->op_array[i];
1771                         mdt = LTD_TGT(ltd, mdt_idx);
1772
1773                         if (!mdt->ltd_qos.ltq_usable)
1774                                 continue;
1775
1776                         cur_weight += mdt->ltd_qos.ltq_weight;
1777
1778                         QOS_DEBUG("stripe_count=%d stripe_index=%d cur_weight=%llu rand=%llu total_weight=%llu\n",
1779                                   stripe_count, stripe_idx, cur_weight, rand,
1780                                   total_weight);
1781
1782                         if (cur_weight < rand)
1783                                 continue;
1784
1785                         QOS_DEBUG("stripe=%d to idx=%d\n",
1786                                   stripe_idx, mdt_idx);
1787
1788                         if (lod_qos_is_tgt_used(env, mdt_idx, stripe_idx))
1789                                 continue;
1790
1791                         rc2 = dt_fid_alloc(env, mdt->ltd_tgt, &fid, NULL, NULL);
1792                         if (rc2 < 0) {
1793                                 QOS_DEBUG("can't alloc FID on #%u: %d\n",
1794                                           mdt_idx, rc2);
1795                                 continue;
1796                         }
1797
1798                         conf.loc_flags = LOC_F_NEW;
1799                         dto = dt_locate_at(env, mdt->ltd_tgt, &fid,
1800                                 lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
1801                                 &conf);
1802                         if (IS_ERR(dto)) {
1803                                 QOS_DEBUG("can't alloc stripe on #%u: %d\n",
1804                                           mdt_idx, (int) PTR_ERR(dto));
1805                                 continue;
1806                         }
1807
1808                         lod_qos_tgt_in_use(env, stripe_idx, mdt_idx);
1809                         stripes[stripe_idx] = dto;
1810                         ltd_qos_update(ltd, mdt, &total_weight);
1811                         stripe_idx++;
1812                         rc = 0;
1813                         break;
1814                 }
1815
1816                 /* no MDT found on this iteration, give up */
1817                 if (rc)
1818                         break;
1819         }
1820
1821         if (unlikely(stripe_idx != stripe_count)) {
1822                 /*
1823                  * when the decision to use weighted algorithm was made
1824                  * we had enough appropriate OSPs, but this state can
1825                  * change anytime (no space on MDT, broken connection, etc)
1826                  * so it's possible OSP won't be able to provide us with
1827                  * an object due to just changed state
1828                  */
1829                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1830                           lod2obd(lod)->obd_name, stripe_count, stripe_idx);
1831                 for (i = saved_idx; i < stripe_idx; i++) {
1832                         LASSERT(stripes[i] != NULL);
1833                         dt_object_put(env, stripes[i]);
1834                         stripes[i] = NULL;
1835                 }
1836
1837                 /* makes sense to rebalance next time */
1838                 set_bit(LQ_DIRTY, &ltd->ltd_qos.lq_flags);
1839                 clear_bit(LQ_SAME_SPACE, &ltd->ltd_qos.lq_flags);
1840
1841                 rc = -EAGAIN;
1842         } else {
1843                 rc = stripe_idx;
1844         }
1845
1846 unlock:
1847         up_write(&ltd->ltd_qos.lq_rw_sem);
1848
1849         RETURN(rc);
1850 }
1851
1852 /**
1853  * Check stripe count the caller can use.
1854  *
1855  * For new layouts (no initialized components), check the total size of the
1856  * layout against the maximum EA size from the backing file system.  This
1857  * stops us from creating a layout which will be too large once initialized.
1858  *
1859  * For existing layouts (with initialized components):
1860  * Find the maximal possible stripe count not greater than \a stripe_count.
1861  * If the provided stripe count is 0, then the filesystem's default is used.
1862  *
1863  * \param[in] lod       LOD device
1864  * \param[in] lo        The lod_object
1865  * \param[in] comp_idx  The component id, which the amount of stripes is
1866                         calculated for
1867  * \param[in] stripe_count      count the caller would like to use
1868  *
1869  * \retval              the maximum usable stripe count
1870  */
1871 __u16 lod_get_stripe_count(struct lod_device *lod, struct lod_object *lo,
1872                            int comp_idx, __u16 stripe_count, bool overstriping)
1873 {
1874         __u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
1875         /* max stripe count is based on OSD ea size */
1876         unsigned int easize = lod->lod_osd_max_easize;
1877         int i;
1878
1879         if (!stripe_count)
1880                 stripe_count =
1881                         lod->lod_ost_descs.ltd_lov_desc.ld_default_stripe_count;
1882         if (!stripe_count)
1883                 stripe_count = 1;
1884         /* Overstriping allows more stripes than targets */
1885         if (stripe_count >
1886                 lod->lod_ost_descs.ltd_lov_desc.ld_active_tgt_count &&
1887             !overstriping)
1888                 stripe_count =
1889                         lod->lod_ost_descs.ltd_lov_desc.ld_active_tgt_count;
1890
1891         if (lo->ldo_is_composite) {
1892                 struct lod_layout_component *lod_comp;
1893                 unsigned int header_sz = sizeof(struct lov_comp_md_v1);
1894                 unsigned int init_comp_sz = 0;
1895                 unsigned int total_comp_sz = 0;
1896                 unsigned int comp_sz;
1897
1898                 header_sz += sizeof(struct lov_comp_md_entry_v1) *
1899                                 lo->ldo_comp_cnt;
1900
1901                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
1902                         unsigned int stripes;
1903
1904                         if (i == comp_idx)
1905                                 continue;
1906
1907                         lod_comp = &lo->ldo_comp_entries[i];
1908                         /* Extension comp is never inited - 0 stripes on disk */
1909                         stripes = lod_comp->llc_flags & LCME_FL_EXTENSION ? 0 :
1910                                 lod_comp->llc_stripe_count;
1911
1912                         comp_sz = lov_mds_md_size(stripes, LOV_MAGIC_V3);
1913                         total_comp_sz += comp_sz;
1914                         if (lod_comp->llc_flags & LCME_FL_INIT)
1915                                 init_comp_sz += comp_sz;
1916                 }
1917
1918                 if (init_comp_sz > 0)
1919                         total_comp_sz = init_comp_sz;
1920
1921                 header_sz += total_comp_sz;
1922
1923                 if (easize > header_sz)
1924                         easize -= header_sz;
1925                 else
1926                         easize = 0;
1927         }
1928
1929         max_stripes = lov_mds_md_max_stripe_count(easize, LOV_MAGIC_V3);
1930         max_stripes = (max_stripes == 0) ? 0 : max_stripes - 1;
1931
1932         return (stripe_count < max_stripes) ? stripe_count : max_stripes;
1933 }
1934
1935 /**
1936  * Create in-core respresentation for a fully-defined striping
1937  *
1938  * When the caller passes a fully-defined striping (i.e. everything including
1939  * OST object FIDs are defined), then we still need to instantiate LU-cache
1940  * with the objects representing the stripes defined. This function completes
1941  * that task.
1942  *
1943  * \param[in] env       execution environment for this thread
1944  * \param[in] mo        LOD object
1945  * \param[in] buf       buffer containing the striping
1946  *
1947  * \retval 0            on success
1948  * \retval negative     negated errno on error
1949  */
1950 int lod_use_defined_striping(const struct lu_env *env,
1951                              struct lod_object *mo,
1952                              const struct lu_buf *buf)
1953 {
1954         struct lod_layout_component *lod_comp;
1955         struct lov_mds_md_v1   *v1 = buf->lb_buf;
1956         struct lov_mds_md_v3   *v3 = buf->lb_buf;
1957         struct lov_comp_md_v1  *comp_v1 = NULL;
1958         struct lov_ost_data_v1 *objs;
1959         __u32   magic;
1960         __u16   comp_cnt;
1961         __u16   mirror_cnt;
1962         int     rc = 0, i;
1963         ENTRY;
1964
1965         mutex_lock(&mo->ldo_layout_mutex);
1966         lod_striping_free_nolock(env, mo);
1967
1968         magic = le32_to_cpu(v1->lmm_magic) & ~LOV_MAGIC_DEFINED;
1969
1970         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3 &&
1971             magic != LOV_MAGIC_COMP_V1 && magic != LOV_MAGIC_FOREIGN)
1972                 GOTO(unlock, rc = -EINVAL);
1973
1974         if (magic == LOV_MAGIC_COMP_V1) {
1975                 comp_v1 = buf->lb_buf;
1976                 comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
1977                 if (comp_cnt == 0)
1978                         GOTO(unlock, rc = -EINVAL);
1979                 mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
1980                 mo->ldo_flr_state = le16_to_cpu(comp_v1->lcm_flags) &
1981                                         LCM_FL_FLR_MASK;
1982                 mo->ldo_is_composite = 1;
1983         } else if (magic == LOV_MAGIC_FOREIGN) {
1984                 struct lov_foreign_md *foreign;
1985                 size_t length;
1986
1987                 if (buf->lb_len < offsetof(typeof(*foreign), lfm_value)) {
1988                         CDEBUG(D_LAYOUT,
1989                                "buf len %zu < min lov_foreign_md size (%zu)\n",
1990                                buf->lb_len,
1991                                offsetof(typeof(*foreign), lfm_value));
1992                         GOTO(out, rc = -EINVAL);
1993                 }
1994                 foreign = (struct lov_foreign_md *)buf->lb_buf;
1995                 length = foreign_size_le(foreign);
1996                 if (buf->lb_len < length) {
1997                         CDEBUG(D_LAYOUT,
1998                                "buf len %zu < this lov_foreign_md size (%zu)\n",
1999                                buf->lb_len, length);
2000                         GOTO(out, rc = -EINVAL);
2001                 }
2002
2003                 /* just cache foreign LOV EA raw */
2004                 rc = lod_alloc_foreign_lov(mo, length);
2005                 if (rc)
2006                         GOTO(out, rc);
2007                 memcpy(mo->ldo_foreign_lov, buf->lb_buf, length);
2008                 GOTO(out, rc);
2009         } else {
2010                 mo->ldo_is_composite = 0;
2011                 comp_cnt = 1;
2012                 mirror_cnt = 0;
2013         }
2014         mo->ldo_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
2015
2016         rc = lod_alloc_comp_entries(mo, mirror_cnt, comp_cnt);
2017         if (rc)
2018                 GOTO(unlock, rc);
2019
2020         for (i = 0; i < comp_cnt; i++) {
2021                 struct lu_extent *ext;
2022                 char    *pool_name;
2023                 __u32   offs;
2024
2025                 lod_comp = &mo->ldo_comp_entries[i];
2026
2027                 if (mo->ldo_is_composite) {
2028                         offs = le32_to_cpu(comp_v1->lcm_entries[i].lcme_offset);
2029                         v1 = (struct lov_mds_md_v1 *)((char *)comp_v1 + offs);
2030                         v3 = (struct lov_mds_md_v3 *)v1;
2031                         magic = le32_to_cpu(v1->lmm_magic);
2032
2033                         ext = &comp_v1->lcm_entries[i].lcme_extent;
2034                         lod_comp->llc_extent.e_start =
2035                                 le64_to_cpu(ext->e_start);
2036                         lod_comp->llc_extent.e_end = le64_to_cpu(ext->e_end);
2037                         lod_comp->llc_flags =
2038                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags);
2039                         if (lod_comp->llc_flags & LCME_FL_NOSYNC)
2040                                 lod_comp->llc_timestamp = le64_to_cpu(
2041                                         comp_v1->lcm_entries[i].lcme_timestamp);
2042                         lod_comp->llc_id =
2043                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_id);
2044                         if (lod_comp->llc_id == LCME_ID_INVAL)
2045                                 GOTO(out, rc = -EINVAL);
2046                 }
2047
2048                 pool_name = NULL;
2049                 if (magic == LOV_MAGIC_V1) {
2050                         objs = &v1->lmm_objects[0];
2051                 } else if (magic == LOV_MAGIC_V3) {
2052                         objs = &v3->lmm_objects[0];
2053                         if (v3->lmm_pool_name[0] != '\0')
2054                                 pool_name = v3->lmm_pool_name;
2055                 } else {
2056                         CDEBUG(D_LAYOUT, "Invalid magic %x\n", magic);
2057                         GOTO(out, rc = -EINVAL);
2058                 }
2059
2060                 lod_comp->llc_pattern = le32_to_cpu(v1->lmm_pattern);
2061                 lod_comp->llc_stripe_size = le32_to_cpu(v1->lmm_stripe_size);
2062                 lod_comp->llc_stripe_count = le16_to_cpu(v1->lmm_stripe_count);
2063                 lod_comp->llc_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
2064                 /**
2065                  * The stripe_offset of an uninit-ed component is stored in
2066                  * the lmm_layout_gen
2067                  */
2068                 if (mo->ldo_is_composite && !lod_comp_inited(lod_comp))
2069                         lod_comp->llc_stripe_offset = lod_comp->llc_layout_gen;
2070                 lod_obj_set_pool(mo, i, pool_name);
2071
2072                 if ((!mo->ldo_is_composite || lod_comp_inited(lod_comp)) &&
2073                     !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
2074                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT)) {
2075                         rc = lod_initialize_objects(env, mo, objs, i);
2076                         if (rc)
2077                                 GOTO(out, rc);
2078                 }
2079         }
2080
2081         rc = lod_fill_mirrors(mo);
2082         GOTO(out, rc);
2083 out:
2084         if (rc)
2085                 lod_striping_free_nolock(env, mo);
2086 unlock:
2087         mutex_unlock(&mo->ldo_layout_mutex);
2088
2089         RETURN(rc);
2090 }
2091
2092 /**
2093  * Parse suggested striping configuration.
2094  *
2095  * The caller gets a suggested striping configuration from a number of sources
2096  * including per-directory default and applications. Then it needs to verify
2097  * the suggested striping is valid, apply missing bits and store the resulting
2098  * configuration in the object to be used by the allocator later. Must not be
2099  * called concurrently against the same object. It's OK to provide a
2100  * fully-defined striping.
2101  *
2102  * \param[in] env       execution environment for this thread
2103  * \param[in] lo        LOD object
2104  * \param[in] buf       buffer containing the striping
2105  *
2106  * \retval 0            on success
2107  * \retval negative     negated errno on error
2108  */
2109 int lod_qos_parse_config(const struct lu_env *env, struct lod_object *lo,
2110                          const struct lu_buf *buf)
2111 {
2112         struct lod_layout_component *lod_comp;
2113         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2114         struct lov_desc *desc = &d->lod_ost_descs.ltd_lov_desc;
2115         struct lov_user_md_v1 *v1 = NULL;
2116         struct lov_user_md_v3 *v3 = NULL;
2117         struct lov_comp_md_v1 *comp_v1 = NULL;
2118         struct lov_foreign_md *lfm = NULL;
2119         char def_pool[LOV_MAXPOOLNAME + 1];
2120         __u32 magic;
2121         __u16 comp_cnt;
2122         __u16 mirror_cnt;
2123         int i, rc;
2124         ENTRY;
2125
2126         if (buf == NULL || buf->lb_buf == NULL || buf->lb_len == 0)
2127                 RETURN(0);
2128
2129         memset(def_pool, 0, sizeof(def_pool));
2130         if (lo->ldo_comp_entries != NULL)
2131                 lod_layout_get_pool(lo->ldo_comp_entries, lo->ldo_comp_cnt,
2132                                     def_pool, sizeof(def_pool));
2133
2134         /* free default striping info */
2135         if (lo->ldo_is_foreign)
2136                 lod_free_foreign_lov(lo);
2137         else
2138                 lod_free_comp_entries(lo);
2139
2140         rc = lod_verify_striping(env, d, lo, buf, false);
2141         if (rc)
2142                 RETURN(-EINVAL);
2143
2144         v3 = buf->lb_buf;
2145         v1 = buf->lb_buf;
2146         comp_v1 = buf->lb_buf;
2147         /* {lmm,lfm}_magic position/length work for all LOV formats */
2148         magic = v1->lmm_magic;
2149
2150         if (unlikely(le32_to_cpu(magic) & LOV_MAGIC_DEFINED)) {
2151                 /* try to use as fully defined striping */
2152                 rc = lod_use_defined_striping(env, lo, buf);
2153                 RETURN(rc);
2154         }
2155
2156         switch (magic) {
2157         case __swab32(LOV_USER_MAGIC_V1):
2158                 lustre_swab_lov_user_md_v1(v1);
2159                 magic = v1->lmm_magic;
2160                 /* fall through */
2161         case LOV_USER_MAGIC_V1:
2162                 break;
2163         case __swab32(LOV_USER_MAGIC_V3):
2164                 lustre_swab_lov_user_md_v3(v3);
2165                 magic = v3->lmm_magic;
2166                 /* fall through */
2167         case LOV_USER_MAGIC_V3:
2168                 break;
2169         case __swab32(LOV_USER_MAGIC_SPECIFIC):
2170                 lustre_swab_lov_user_md_v3(v3);
2171                 lustre_swab_lov_user_md_objects(v3->lmm_objects,
2172                                                 v3->lmm_stripe_count);
2173                 magic = v3->lmm_magic;
2174                 /* fall through */
2175         case LOV_USER_MAGIC_SPECIFIC:
2176                 break;
2177         case __swab32(LOV_USER_MAGIC_COMP_V1):
2178                 lustre_swab_lov_comp_md_v1(comp_v1);
2179                 magic = comp_v1->lcm_magic;
2180                 /* fall trhough */
2181         case LOV_USER_MAGIC_COMP_V1:
2182                 break;
2183         case __swab32(LOV_USER_MAGIC_FOREIGN):
2184                 lfm = buf->lb_buf;
2185                 __swab32s(&lfm->lfm_magic);
2186                 __swab32s(&lfm->lfm_length);
2187                 __swab32s(&lfm->lfm_type);
2188                 __swab32s(&lfm->lfm_flags);
2189                 magic = lfm->lfm_magic;
2190                 /* fall through */
2191         case LOV_USER_MAGIC_FOREIGN:
2192                 if (!lfm)
2193                         lfm = buf->lb_buf;
2194                 rc = lod_alloc_foreign_lov(lo, foreign_size(lfm));
2195                 if (rc)
2196                         RETURN(rc);
2197                 memcpy(lo->ldo_foreign_lov, buf->lb_buf, foreign_size(lfm));
2198                 RETURN(0);
2199         default:
2200                 CERROR("%s: unrecognized magic %X\n",
2201                        lod2obd(d)->obd_name, magic);
2202                 RETURN(-EINVAL);
2203         }
2204
2205         lustre_print_user_md(D_OTHER, v1, "parse config");
2206
2207         if (magic == LOV_USER_MAGIC_COMP_V1) {
2208                 comp_cnt = comp_v1->lcm_entry_count;
2209                 if (comp_cnt == 0)
2210                         RETURN(-EINVAL);
2211                 mirror_cnt =  comp_v1->lcm_mirror_count + 1;
2212                 if (mirror_cnt > 1)
2213                         lo->ldo_flr_state = LCM_FL_RDONLY;
2214                 lo->ldo_is_composite = 1;
2215         } else {
2216                 comp_cnt = 1;
2217                 mirror_cnt = 0;
2218                 lo->ldo_is_composite = 0;
2219         }
2220
2221         rc = lod_alloc_comp_entries(lo, mirror_cnt, comp_cnt);
2222         if (rc)
2223                 RETURN(rc);
2224
2225         LASSERT(lo->ldo_comp_entries);
2226
2227         for (i = 0; i < comp_cnt; i++) {
2228                 struct pool_desc        *pool;
2229                 struct lu_extent        *ext;
2230                 char    *pool_name;
2231
2232                 lod_comp = &lo->ldo_comp_entries[i];
2233
2234                 if (lo->ldo_is_composite) {
2235                         v1 = (struct lov_user_md *)((char *)comp_v1 +
2236                                         comp_v1->lcm_entries[i].lcme_offset);
2237                         ext = &comp_v1->lcm_entries[i].lcme_extent;
2238                         lod_comp->llc_extent = *ext;
2239                         lod_comp->llc_flags =
2240                                 comp_v1->lcm_entries[i].lcme_flags &
2241                                         LCME_CL_COMP_FLAGS;
2242                 }
2243
2244                 pool_name = NULL;
2245                 if (v1->lmm_magic == LOV_USER_MAGIC_V3 ||
2246                     v1->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2247                         v3 = (struct lov_user_md_v3 *)v1;
2248                         if (v3->lmm_pool_name[0] != '\0')
2249                                 pool_name = v3->lmm_pool_name;
2250
2251                         if (v3->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2252                                 rc = lod_comp_copy_ost_lists(lod_comp, v3);
2253                                 if (rc)
2254                                         GOTO(free_comp, rc);
2255                         }
2256                 }
2257
2258                 if (pool_name == NULL && def_pool[0] != '\0')
2259                         pool_name = def_pool;
2260
2261                 if (v1->lmm_pattern == 0)
2262                         v1->lmm_pattern = LOV_PATTERN_RAID0;
2263                 if (lov_pattern(v1->lmm_pattern) != LOV_PATTERN_RAID0 &&
2264                     lov_pattern(v1->lmm_pattern) != LOV_PATTERN_MDT &&
2265                     lov_pattern(v1->lmm_pattern) !=
2266                         (LOV_PATTERN_RAID0 | LOV_PATTERN_OVERSTRIPING)) {
2267                         CDEBUG(D_LAYOUT, "%s: invalid pattern: %x\n",
2268                                lod2obd(d)->obd_name, v1->lmm_pattern);
2269                         GOTO(free_comp, rc = -EINVAL);
2270                 }
2271
2272                 lod_comp->llc_pattern = v1->lmm_pattern;
2273                 lod_comp->llc_stripe_size = v1->lmm_stripe_size;
2274                 lod_adjust_stripe_size(lod_comp, desc->ld_default_stripe_size);
2275
2276                 lod_comp->llc_stripe_count = desc->ld_default_stripe_count;
2277                 if (v1->lmm_stripe_count ||
2278                     lov_pattern(v1->lmm_pattern) == LOV_PATTERN_MDT)
2279                         lod_comp->llc_stripe_count = v1->lmm_stripe_count;
2280
2281                 if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT &&
2282                     lod_comp->llc_stripe_count != 0) {
2283                         CDEBUG(D_LAYOUT, "%s: invalid stripe count: %u\n",
2284                                lod2obd(d)->obd_name,
2285                                lod_comp->llc_stripe_count);
2286                         GOTO(free_comp, rc = -EINVAL);
2287                 }
2288
2289                 lod_comp->llc_stripe_offset = v1->lmm_stripe_offset;
2290                 lod_obj_set_pool(lo, i, pool_name);
2291
2292                 if (pool_name == NULL)
2293                         continue;
2294
2295                 /* In the function below, .hs_keycmp resolves to
2296                  * pool_hashkey_keycmp() */
2297                 /* coverity[overrun-buffer-val] */
2298                 pool = lod_find_pool(d, pool_name);
2299                 if (pool == NULL)
2300                         continue;
2301
2302                 if (lod_comp->llc_stripe_offset != LOV_OFFSET_DEFAULT) {
2303                         rc = lod_check_index_in_pool(
2304                                         lod_comp->llc_stripe_offset, pool);
2305                         if (rc < 0) {
2306                                 lod_pool_putref(pool);
2307                                 CDEBUG(D_LAYOUT, "%s: invalid offset, %u\n",
2308                                        lod2obd(d)->obd_name,
2309                                        lod_comp->llc_stripe_offset);
2310                                 GOTO(free_comp, rc = -EINVAL);
2311                         }
2312                 }
2313
2314                 if (lod_comp->llc_stripe_count > pool_tgt_count(pool) &&
2315                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
2316                         lod_comp->llc_stripe_count = pool_tgt_count(pool);
2317
2318                 lod_pool_putref(pool);
2319         }
2320
2321         RETURN(0);
2322
2323 free_comp:
2324         lod_free_comp_entries(lo);
2325         RETURN(rc);
2326 }
2327
2328 /**
2329  * prepare enough OST avoidance bitmap space
2330  */
2331 int lod_prepare_avoidance(const struct lu_env *env, struct lod_object *lo)
2332 {
2333         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2334         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2335         unsigned long *bitmap = NULL;
2336         __u32 *new_oss = NULL;
2337
2338         lag->lag_ost_avail = lod->lod_ost_count;
2339
2340         /* reset OSS avoid guide array */
2341         lag->lag_oaa_count = 0;
2342         if (lag->lag_oss_avoid_array &&
2343             lag->lag_oaa_size < lod->lod_ost_count) {
2344                 OBD_FREE_PTR_ARRAY(lag->lag_oss_avoid_array, lag->lag_oaa_size);
2345                 lag->lag_oss_avoid_array = NULL;
2346                 lag->lag_oaa_size = 0;
2347         }
2348
2349         /* init OST avoid guide bitmap */
2350         if (lag->lag_ost_avoid_bitmap) {
2351                 if (lod->lod_ost_count <= lag->lag_ost_avoid_size) {
2352                         bitmap_zero(lag->lag_ost_avoid_bitmap,
2353                                     lag->lag_ost_avoid_size);
2354                 } else {
2355                         bitmap_free(lag->lag_ost_avoid_bitmap);
2356                         lag->lag_ost_avoid_bitmap = NULL;
2357                 }
2358         }
2359
2360         if (!lag->lag_ost_avoid_bitmap) {
2361                 bitmap = bitmap_zalloc(lod->lod_ost_count, GFP_KERNEL);
2362                 if (!bitmap)
2363                         return -ENOMEM;
2364         }
2365
2366         if (!lag->lag_oss_avoid_array) {
2367                 /**
2368                  * usually there are multiple OSTs in one OSS, but we don't
2369                  * know the exact OSS number, so we choose a safe option,
2370                  * using OST count to allocate the array to store the OSS
2371                  * id.
2372                  */
2373                 OBD_ALLOC_PTR_ARRAY(new_oss, lod->lod_ost_count);
2374                 if (!new_oss) {
2375                         bitmap_free(bitmap);
2376                         return -ENOMEM;
2377                 }
2378         }
2379
2380         if (new_oss) {
2381                 lag->lag_oss_avoid_array = new_oss;
2382                 lag->lag_oaa_size = lod->lod_ost_count;
2383         }
2384         if (bitmap) {
2385                 lag->lag_ost_avoid_bitmap = bitmap;
2386                 lag->lag_ost_avoid_size = lod->lod_ost_count;
2387         }
2388
2389         return 0;
2390 }
2391
2392 /**
2393  * Collect information of used OSTs and OSSs in the overlapped components
2394  * of other mirrors
2395  */
2396 void lod_collect_avoidance(struct lod_object *lo, struct lod_avoid_guide *lag,
2397                            int comp_idx)
2398 {
2399         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2400         struct lod_layout_component *lod_comp = &lo->ldo_comp_entries[comp_idx];
2401         unsigned long *bitmap = lag->lag_ost_avoid_bitmap;
2402         int i, j;
2403
2404         /* iterate mirrors */
2405         for (i = 0; i < lo->ldo_mirror_count; i++) {
2406                 struct lod_layout_component *comp;
2407
2408                 /**
2409                  * skip mirror containing component[comp_idx], we only
2410                  * collect OSTs info of conflicting component in other mirrors,
2411                  * so that during read, if OSTs of a mirror's component are
2412                  * not available, we still have other mirror with different
2413                  * OSTs to read the data.
2414                  */
2415                 comp = &lo->ldo_comp_entries[lo->ldo_mirrors[i].lme_start];
2416                 if (comp->llc_id != LCME_ID_INVAL &&
2417                     mirror_id_of(comp->llc_id) ==
2418                                                 mirror_id_of(lod_comp->llc_id))
2419                         continue;
2420
2421                 /* iterate components of a mirror */
2422                 lod_foreach_mirror_comp(comp, lo, i) {
2423                         /**
2424                          * skip non-overlapped or un-instantiated components,
2425                          * NOTE: don't use lod_comp_inited(comp) to judge
2426                          * whether @comp has been inited, since during
2427                          * declare phase, comp->llc_stripe has been allocated
2428                          * while it's init flag not been set until the exec
2429                          * phase.
2430                          */
2431                         if (!lu_extent_is_overlapped(&comp->llc_extent,
2432                                                      &lod_comp->llc_extent) ||
2433                             !comp->llc_stripe)
2434                                 continue;
2435
2436                         /**
2437                          * collect used OSTs index and OSS info from a
2438                          * component
2439                          */
2440                         for (j = 0; j < comp->llc_stripe_count; j++) {
2441                                 struct lod_tgt_desc *ost;
2442                                 struct lu_svr_qos *lsq;
2443                                 int k;
2444
2445                                 ost = OST_TGT(lod, comp->llc_ost_indices[j]);
2446                                 lsq = ost->ltd_qos.ltq_svr;
2447
2448                                 if (test_bit(ost->ltd_index, bitmap))
2449                                         continue;
2450
2451                                 QOS_DEBUG("OST%d used in conflicting mirror "
2452                                           "component\n", ost->ltd_index);
2453                                 set_bit(ost->ltd_index, bitmap);
2454                                 lag->lag_ost_avail--;
2455
2456                                 for (k = 0; k < lag->lag_oaa_count; k++) {
2457                                         if (lag->lag_oss_avoid_array[k] ==
2458                                             lsq->lsq_id)
2459                                                 break;
2460                                 }
2461                                 if (k == lag->lag_oaa_count) {
2462                                         lag->lag_oss_avoid_array[k] =
2463                                                                 lsq->lsq_id;
2464                                         lag->lag_oaa_count++;
2465                                 }
2466                         }
2467                 }
2468         }
2469 }
2470
2471 /**
2472  * Create a striping for an obejct.
2473  *
2474  * The function creates a new striping for the object. The function tries QoS
2475  * algorithm first unless free space is distributed evenly among OSTs, but
2476  * by default RR algorithm is preferred due to internal concurrency (QoS is
2477  * serialized). The caller must ensure no concurrent calls to the function
2478  * are made against the same object.
2479  *
2480  * \param[in] env       execution environment for this thread
2481  * \param[in] lo        LOD object
2482  * \param[in] attr      attributes OST objects will be declared with
2483  * \param[in] th        transaction handle
2484  * \param[in] comp_idx  index of ldo_comp_entries
2485  *
2486  * \retval 0            on success
2487  * \retval negative     negated errno on error
2488  */
2489 int lod_qos_prep_create(const struct lu_env *env, struct lod_object *lo,
2490                         struct lu_attr *attr, struct thandle *th,
2491                         int comp_idx, __u64 reserve)
2492 {
2493         struct lod_layout_component *lod_comp;
2494         struct lod_device      *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2495         int                     stripe_len;
2496         int                     flag = LOV_USES_ASSIGNED_STRIPE;
2497         int                     i, rc = 0;
2498         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2499         struct dt_object **stripe = NULL;
2500         __u32 *ost_indices = NULL;
2501         ENTRY;
2502
2503         LASSERT(lo);
2504         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
2505         lod_comp = &lo->ldo_comp_entries[comp_idx];
2506         LASSERT(!(lod_comp->llc_flags & LCME_FL_EXTENSION));
2507
2508         /* A released component is being created */
2509         if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
2510                 RETURN(0);
2511
2512         /* A Data-on-MDT component is being created */
2513         if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT)
2514                 RETURN(0);
2515
2516         if (likely(lod_comp->llc_stripe == NULL)) {
2517                 /*
2518                  * no striping has been created so far
2519                  */
2520                 LASSERT(lod_comp->llc_stripe_count);
2521                 /*
2522                  * statfs and check OST targets now, since ld_active_tgt_count
2523                  * could be changed if some OSTs are [de]activated manually.
2524                  */
2525                 lod_qos_statfs_update(env, d, &d->lod_ost_descs);
2526                 stripe_len = lod_get_stripe_count(d, lo, comp_idx,
2527                                                   lod_comp->llc_stripe_count,
2528                                                   lod_comp->llc_pattern &
2529                                                   LOV_PATTERN_OVERSTRIPING);
2530
2531                 if (stripe_len == 0)
2532                         GOTO(out, rc = -ERANGE);
2533                 lod_comp->llc_stripe_count = stripe_len;
2534                 OBD_ALLOC_PTR_ARRAY(stripe, stripe_len);
2535                 if (stripe == NULL)
2536                         GOTO(out, rc = -ENOMEM);
2537                 OBD_ALLOC_PTR_ARRAY(ost_indices, stripe_len);
2538                 if (!ost_indices)
2539                         GOTO(out, rc = -ENOMEM);
2540
2541 repeat:
2542                 lod_getref(&d->lod_ost_descs);
2543                 /* XXX: support for non-0 files w/o objects */
2544                 CDEBUG(D_OTHER, "tgt_count %d stripe_count %d\n",
2545                        d->lod_ost_count, stripe_len);
2546
2547                 if (lod_comp->llc_ostlist.op_array &&
2548                     lod_comp->llc_ostlist.op_count) {
2549                         rc = lod_alloc_ost_list(env, lo, stripe, ost_indices,
2550                                                 th, comp_idx, reserve);
2551                 } else if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT) {
2552                         /**
2553                          * collect OSTs and OSSs used in other mirrors whose
2554                          * components cross the ldo_comp_entries[comp_idx]
2555                          */
2556                         rc = lod_prepare_avoidance(env, lo);
2557                         if (rc)
2558                                 GOTO(put_ldts, rc);
2559
2560                         QOS_DEBUG("collecting conflict osts for comp[%d]\n",
2561                                   comp_idx);
2562                         lod_collect_avoidance(lo, lag, comp_idx);
2563
2564                         rc = lod_ost_alloc_qos(env, lo, stripe, ost_indices,
2565                                                flag, th, comp_idx, reserve);
2566                         if (rc == -EAGAIN)
2567                                 rc = lod_ost_alloc_rr(env, lo, stripe,
2568                                                       ost_indices, flag, th,
2569                                                       comp_idx, reserve);
2570                 } else {
2571                         rc = lod_ost_alloc_specific(env, lo, stripe,
2572                                                     ost_indices, flag, th,
2573                                                     comp_idx, reserve);
2574                 }
2575 put_ldts:
2576                 lod_putref(d, &d->lod_ost_descs);
2577                 if (rc < 0) {
2578                         for (i = 0; i < stripe_len; i++)
2579                                 if (stripe[i] != NULL)
2580                                         dt_object_put(env, stripe[i]);
2581
2582                         /* In case there is no space on any OST, let's ignore
2583                          * the @reserve space to avoid an error at the init
2584                          * time, probably the actual IO will be less than the
2585                          * given @reserve space (aka extension_size). */
2586                         if (reserve) {
2587                                 reserve = 0;
2588                                 goto repeat;
2589                         }
2590                         lod_comp->llc_stripe_count = 0;
2591                 } else {
2592                         lod_comp->llc_stripe = stripe;
2593                         lod_comp->llc_ost_indices = ost_indices;
2594                         lod_comp->llc_stripes_allocated = stripe_len;
2595                 }
2596         } else {
2597                 /*
2598                  * lod_qos_parse_config() found supplied buf as a predefined
2599                  * striping (not a hint), so it allocated all the object
2600                  * now we need to create them
2601                  */
2602                 for (i = 0; i < lod_comp->llc_stripe_count; i++) {
2603                         struct dt_object  *o;
2604
2605                         o = lod_comp->llc_stripe[i];
2606                         LASSERT(o);
2607
2608                         rc = lod_sub_declare_create(env, o, attr, NULL,
2609                                                     NULL, th);
2610                         if (rc < 0) {
2611                                 CERROR("can't declare create: %d\n", rc);
2612                                 break;
2613                         }
2614                 }
2615                 /**
2616                  * Clear LCME_FL_INIT for the component so that
2617                  * lod_striping_create() can create the striping objects
2618                  * in replay.
2619                  */
2620                 lod_comp_unset_init(lod_comp);
2621         }
2622
2623 out:
2624         if (rc < 0) {
2625                 if (stripe)
2626                         OBD_FREE_PTR_ARRAY(stripe, stripe_len);
2627                 if (ost_indices)
2628                         OBD_FREE_PTR_ARRAY(ost_indices, stripe_len);
2629         }
2630         RETURN(rc);
2631 }
2632
2633 int lod_prepare_create(const struct lu_env *env, struct lod_object *lo,
2634                        struct lu_attr *attr, const struct lu_buf *buf,
2635                        struct thandle *th)
2636
2637 {
2638         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2639         uint64_t size = 0;
2640         int i;
2641         int rc;
2642         ENTRY;
2643
2644         LASSERT(lo);
2645
2646         /* no OST available */
2647         /* XXX: should we be waiting a bit to prevent failures during
2648          * cluster initialization? */
2649         if (!d->lod_ost_count)
2650                 RETURN(-EIO);
2651
2652         /*
2653          * by this time, the object's ldo_stripe_count and ldo_stripe_size
2654          * contain default value for striping: taken from the parent
2655          * or from filesystem defaults
2656          *
2657          * in case the caller is passing lovea with new striping config,
2658          * we may need to parse lovea and apply new configuration
2659          */
2660         rc = lod_qos_parse_config(env, lo, buf);
2661         if (rc)
2662                 RETURN(rc);
2663
2664         if (attr->la_valid & LA_SIZE)
2665                 size = attr->la_size;
2666
2667         /**
2668          * prepare OST object creation for the component covering file's
2669          * size, the 1st component (including plain layout file) is always
2670          * instantiated.
2671          */
2672         for (i = 0; i < lo->ldo_comp_cnt; i++) {
2673                 struct lod_layout_component *lod_comp;
2674                 struct lu_extent *extent;
2675
2676                 lod_comp = &lo->ldo_comp_entries[i];
2677                 extent = &lod_comp->llc_extent;
2678                 QOS_DEBUG("comp[%d] %lld "DEXT"\n", i, size, PEXT(extent));
2679                 if (!lo->ldo_is_composite || size >= extent->e_start) {
2680                         rc = lod_qos_prep_create(env, lo, attr, th, i, 0);
2681                         if (rc)
2682                                 break;
2683                 }
2684         }
2685
2686         RETURN(rc);
2687 }