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