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