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