Whamcloud - gitweb
LU-16524 sec: add fscrypt_admin rbac role
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.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 (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2017, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <linux/kernel.h>
43 #include <obd_support.h>
44 #include <lustre_export.h>
45 #include <obd.h>
46 #include <lprocfs_status.h>
47 #include <lustre_log.h>
48 #include <lustre_kernelcomm.h>
49 #include "mdt_internal.h"
50
51 /**
52  * get obj and HSM attributes on a fid
53  * \param mti [IN] context
54  * \param fid [IN] object fid
55  * \param hsm [OUT] HSM meta data
56  * \retval obj or error (-ENOENT if not found)
57  */
58 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
59                                       const struct lu_fid *fid,
60                                       struct md_hsm *hsm)
61 {
62         struct md_attr          *ma;
63         struct mdt_object       *obj;
64         int                      rc;
65         ENTRY;
66
67         ma = &mti->mti_attr;
68         ma->ma_need = MA_HSM;
69         ma->ma_valid = 0;
70
71         /* find object by FID */
72         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
73         if (IS_ERR(obj))
74                 RETURN(obj);
75
76         if (!mdt_object_exists(obj)) {
77                 /* no more object */
78                 mdt_object_put(mti->mti_env, obj);
79                 RETURN(ERR_PTR(-ENOENT));
80         }
81
82         rc = mdt_attr_get_complex(mti, obj, ma);
83         if (rc) {
84                 mdt_object_put(mti->mti_env, obj);
85                 RETURN(ERR_PTR(rc));
86         }
87
88         if (ma->ma_valid & MA_HSM)
89                 *hsm = ma->ma_hsm;
90         else
91                 memset(hsm, 0, sizeof(*hsm));
92         ma->ma_valid = 0;
93         RETURN(obj);
94 }
95
96 void mdt_hsm_dump_hal(int level, const char *prefix,
97                       struct hsm_action_list *hal)
98 {
99         int                      i, sz;
100         struct hsm_action_item  *hai;
101         char                     buf[12];
102
103         CDEBUG(level, "%s: HAL header: version %X count %d"
104                       " archive_id %d flags %#llx\n",
105                prefix, hal->hal_version, hal->hal_count,
106                hal->hal_archive_id, hal->hal_flags);
107
108         hai = hai_first(hal);
109         for (i = 0; i < hal->hal_count; i++) {
110                 sz = hai->hai_len - sizeof(*hai);
111                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
112                        " cookie=%#llx"
113                        " action=%s extent=%#llx-%#llx gid=%#llx"
114                        " datalen=%d data=[%s]\n",
115                        prefix, i,
116                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
117                        hai->hai_cookie,
118                        hsm_copytool_action2name(hai->hai_action),
119                        hai->hai_extent.offset,
120                        hai->hai_extent.length,
121                        hai->hai_gid, sz,
122                        hai_dump_data_field(hai, buf, sizeof(buf)));
123                 hai = hai_next(hai);
124         }
125 }
126
127 /**
128  * data passed to llog_cat_process() callback
129  * to scan requests and take actions
130  */
131 struct hsm_scan_request {
132         int                      hal_sz;
133         int                      hal_used_sz;
134         struct hsm_action_list  *hal;
135 };
136
137 struct hsm_scan_data {
138         struct mdt_thread_info  *hsd_mti;
139         char                     hsd_fsname[MTI_NAME_MAXLEN + 1];
140         /* are we scanning the logs for housekeeping, or just looking
141          * for new work?
142          */
143         bool                     hsd_housekeeping;
144         bool                     hsd_one_restore;
145         u32                      hsd_start_cat_idx;
146         u32                      hsd_start_rec_idx;
147         int                      hsd_action_count;
148         int                      hsd_request_len; /* array alloc len */
149         int                      hsd_request_count; /* array used count */
150         struct hsm_scan_request *hsd_request;
151 };
152
153 static int mdt_cdt_waiting_cb(const struct lu_env *env,
154                               struct mdt_device *mdt,
155                               struct llog_handle *llh,
156                               struct llog_agent_req_rec *larr,
157                               struct hsm_scan_data *hsd)
158 {
159         struct coordinator *cdt = &mdt->mdt_coordinator;
160         struct hsm_scan_request *request;
161         struct hsm_action_item *hai;
162         size_t hai_size;
163         u32 archive_id;
164         bool wrapped;
165         int i;
166
167         /* Are agents full? */
168         if (atomic_read(&cdt->cdt_request_count) >= cdt->cdt_max_requests)
169                 RETURN(hsd->hsd_housekeeping ? 0 : LLOG_PROC_BREAK);
170
171         if (hsd->hsd_action_count + atomic_read(&cdt->cdt_request_count) >=
172             cdt->cdt_max_requests) {
173                 /* We cannot send any more request
174                  *
175                  *                     *** SPECIAL CASE ***
176                  *
177                  * Restore requests are too important not to schedule at least
178                  * one, everytime we can.
179                  */
180                 if (larr->arr_hai.hai_action != HSMA_RESTORE ||
181                     hsd->hsd_one_restore)
182                         RETURN(hsd->hsd_housekeeping ? 0 : LLOG_PROC_BREAK);
183         }
184
185         hai_size = cfs_size_round(larr->arr_hai.hai_len);
186         archive_id = larr->arr_archive_id;
187
188         /* Can we add this action to one of the existing HALs in hsd. */
189         request = NULL;
190         for (i = 0; i < hsd->hsd_request_count; i++) {
191                 if (hsd->hsd_request[i].hal->hal_archive_id == archive_id &&
192                     hsd->hsd_request[i].hal_used_sz + hai_size <=
193                     LDLM_MAXREQSIZE) {
194                         request = &hsd->hsd_request[i];
195                         break;
196                 }
197         }
198
199         /* Are we trying to force-schedule a request? */
200         if (hsd->hsd_action_count + atomic_read(&cdt->cdt_request_count) >=
201             cdt->cdt_max_requests) {
202                 /* Is there really no compatible hsm_scan_request? */
203                 if (!request) {
204                         for (i -= 1; i >= 0; i--) {
205                                 if (hsd->hsd_request[i].hal->hal_archive_id ==
206                                     archive_id) {
207                                         request = &hsd->hsd_request[i];
208                                         break;
209                                 }
210                         }
211                 }
212
213                 /* Make room for the hai */
214                 if (request) {
215                         /* Discard the last hai until there is enough space */
216                         do {
217                                 request->hal->hal_count--;
218
219                                 hai = hai_first(request->hal);
220                                 for (i = 0; i < request->hal->hal_count; i++)
221                                         hai = hai_next(hai);
222                                 request->hal_used_sz -=
223                                         cfs_size_round(hai->hai_len);
224                                 hsd->hsd_action_count--;
225                         } while (request->hal_used_sz + hai_size >
226                                  LDLM_MAXREQSIZE);
227                 } else if (hsd->hsd_housekeeping) {
228                         struct hsm_scan_request *tmp;
229
230                         /* Discard the (whole) last hal */
231                         hsd->hsd_request_count--;
232                         LASSERT(hsd->hsd_request_count >= 0);
233                         tmp = &hsd->hsd_request[hsd->hsd_request_count];
234                         hsd->hsd_action_count -= tmp->hal->hal_count;
235                         LASSERT(hsd->hsd_action_count >= 0);
236                         OBD_FREE(tmp->hal, tmp->hal_sz);
237                 } else {
238                         /* Bailing out, this code path is too hot */
239                         RETURN(LLOG_PROC_BREAK);
240
241                 }
242         }
243
244         if (!request) {
245                 struct hsm_action_list *hal;
246
247                 LASSERT(hsd->hsd_request_count < hsd->hsd_request_len);
248                 request = &hsd->hsd_request[hsd->hsd_request_count];
249
250                 /* allocates hai vector size just needs to be large
251                  * enough */
252                 request->hal_sz = sizeof(*request->hal) +
253                         cfs_size_round(MTI_NAME_MAXLEN + 1) + 2 * hai_size;
254                 OBD_ALLOC_LARGE(hal, request->hal_sz);
255                 if (!hal)
256                         RETURN(-ENOMEM);
257
258                 hal->hal_version = HAL_VERSION;
259                 strlcpy(hal->hal_fsname, hsd->hsd_fsname, MTI_NAME_MAXLEN + 1);
260                 hal->hal_archive_id = larr->arr_archive_id;
261                 hal->hal_flags = larr->arr_flags;
262                 hal->hal_count = 0;
263                 request->hal_used_sz = hal_size(hal);
264                 request->hal = hal;
265                 hsd->hsd_request_count++;
266         } else if (request->hal_sz < request->hal_used_sz + hai_size) {
267                 /* Not enough room, need an extension */
268                 void *hal_buffer;
269                 int sz;
270
271                 sz = min_t(int, 2 * request->hal_sz, LDLM_MAXREQSIZE);
272                 LASSERT(request->hal_used_sz + hai_size < sz);
273
274                 OBD_ALLOC_LARGE(hal_buffer, sz);
275                 if (!hal_buffer)
276                         RETURN(-ENOMEM);
277
278                 memcpy(hal_buffer, request->hal, request->hal_used_sz);
279                 OBD_FREE_LARGE(request->hal, request->hal_sz);
280                 request->hal = hal_buffer;
281                 request->hal_sz = sz;
282         }
283
284         hai = hai_first(request->hal);
285         for (i = 0; i < request->hal->hal_count; i++)
286                 hai = hai_next(hai);
287
288         memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
289
290         request->hal_used_sz += hai_size;
291         request->hal->hal_count++;
292
293         hsd->hsd_action_count++;
294
295         switch (hai->hai_action) {
296         case HSMA_CANCEL:
297                 break;
298         case HSMA_RESTORE:
299                 hsd->hsd_one_restore = true;
300                 fallthrough;
301         default:
302                 cdt_agent_record_hash_add(cdt, hai->hai_cookie,
303                                           llh->lgh_hdr->llh_cat_idx,
304                                           larr->arr_hdr.lrh_index);
305         }
306
307         wrapped = llh->lgh_hdr->llh_cat_idx >= llh->lgh_last_idx &&
308                   llh->lgh_hdr->llh_count > 1;
309         if ((!wrapped && llh->lgh_hdr->llh_cat_idx > hsd->hsd_start_cat_idx) ||
310             (wrapped && llh->lgh_hdr->llh_cat_idx < hsd->hsd_start_cat_idx) ||
311             (llh->lgh_hdr->llh_cat_idx == hsd->hsd_start_cat_idx &&
312              larr->arr_hdr.lrh_index > hsd->hsd_start_rec_idx)) {
313                 hsd->hsd_start_cat_idx = llh->lgh_hdr->llh_cat_idx;
314                 hsd->hsd_start_rec_idx = larr->arr_hdr.lrh_index;
315         }
316
317         RETURN(0);
318 }
319
320 static int mdt_cdt_started_cb(const struct lu_env *env,
321                               struct mdt_device *mdt,
322                               struct llog_handle *llh,
323                               struct llog_agent_req_rec *larr,
324                               struct hsm_scan_data *hsd)
325 {
326         struct coordinator *cdt = &mdt->mdt_coordinator;
327         struct hsm_action_item *hai = &larr->arr_hai;
328         struct cdt_agent_req *car;
329         time64_t now = ktime_get_real_seconds();
330         time64_t last;
331         enum changelog_rec_flags clf_flags;
332         int rc;
333
334         if (!hsd->hsd_housekeeping)
335                 RETURN(0);
336
337         /* we search for a running request
338          * error may happen if coordinator crashes or stopped
339          * with running request
340          */
341         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
342         if (car == NULL) {
343                 last = larr->arr_req_change;
344         } else {
345                 last = car->car_req_update;
346         }
347
348         /* test if request too long, if yes cancel it
349          * the same way the copy tool acknowledge a cancel request */
350         if (now <= last + cdt->cdt_active_req_timeout)
351                 GOTO(out_car, rc = 0);
352
353         dump_llog_agent_req_rec("request timed out, start cleaning", larr);
354
355         if (car != NULL) {
356                 car->car_req_update = now;
357                 mdt_hsm_agent_update_statistics(cdt, 0, 1, 0, &car->car_uuid);
358                 /* Remove car from memory list (LU-9075) */
359                 mdt_cdt_remove_request(cdt, hai->hai_cookie);
360         }
361
362         /* Emit a changelog record for the failed action.*/
363         clf_flags = 0;
364         hsm_set_cl_error(&clf_flags, ECANCELED);
365
366         switch (hai->hai_action) {
367         case HSMA_ARCHIVE:
368                 hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
369                 break;
370         case HSMA_RESTORE:
371                 hsm_set_cl_event(&clf_flags, HE_RESTORE);
372                 break;
373         case HSMA_REMOVE:
374                 hsm_set_cl_event(&clf_flags, HE_REMOVE);
375                 break;
376         case HSMA_CANCEL:
377                 hsm_set_cl_event(&clf_flags, HE_CANCEL);
378                 break;
379         default:
380                 /* Unknown record type, skip changelog. */
381                 clf_flags = 0;
382                 break;
383         }
384
385         if (clf_flags != 0)
386                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
387                              &hai->hai_fid);
388
389         if (hai->hai_action == HSMA_RESTORE)
390                 cdt_restore_handle_del(hsd->hsd_mti, cdt, &hai->hai_fid);
391
392         larr->arr_status = ARS_CANCELED;
393         larr->arr_req_change = now;
394         rc = llog_write(hsd->hsd_mti->mti_env, llh, &larr->arr_hdr,
395                         larr->arr_hdr.lrh_index);
396         if (rc < 0) {
397                 CERROR("%s: cannot update agent log: rc = %d\n",
398                        mdt_obd_name(mdt), rc);
399                 rc = LLOG_DEL_RECORD;
400         }
401
402         /* ct has completed a request, so a slot is available,
403          * signal the coordinator to find new work */
404         mdt_hsm_cdt_event(cdt);
405 out_car:
406         if (car != NULL)
407                 mdt_cdt_put_request(car);
408
409         RETURN(rc);
410 }
411
412 /**
413  *  llog_cat_process() callback, used to:
414  *  - find waiting request and start action
415  *  - purge canceled and done requests
416  * \param env [IN] environment
417  * \param llh [IN] llog handle
418  * \param hdr [IN] llog record
419  * \param data [IN/OUT] cb data = struct hsm_scan_data
420  * \retval 0 success
421  * \retval -ve failure
422  */
423 static int mdt_coordinator_cb(const struct lu_env *env,
424                               struct llog_handle *llh,
425                               struct llog_rec_hdr *hdr,
426                               void *data)
427 {
428         struct llog_agent_req_rec *larr = (struct llog_agent_req_rec *)hdr;
429         struct hsm_scan_data *hsd = data;
430         struct mdt_device *mdt = hsd->hsd_mti->mti_mdt;
431         struct coordinator *cdt = &mdt->mdt_coordinator;
432         ENTRY;
433
434         larr = (struct llog_agent_req_rec *)hdr;
435         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
436         switch (larr->arr_status) {
437         case ARS_WAITING:
438                 RETURN(mdt_cdt_waiting_cb(env, mdt, llh, larr, hsd));
439         case ARS_STARTED:
440                 RETURN(mdt_cdt_started_cb(env, mdt, llh, larr, hsd));
441         default:
442                 if (!hsd->hsd_housekeeping)
443                         RETURN(0);
444
445                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
446                     ktime_get_real_seconds()) {
447                         cdt_agent_record_hash_del(cdt,
448                                                   larr->arr_hai.hai_cookie);
449                         RETURN(LLOG_DEL_RECORD);
450                 }
451
452                 RETURN(0);
453         }
454 }
455
456 /* Release the ressource used by the coordinator. Called when the
457  * coordinator is stopping. */
458 static void mdt_hsm_cdt_cleanup(struct mdt_device *mdt)
459 {
460         struct coordinator              *cdt = &mdt->mdt_coordinator;
461         struct cdt_agent_req            *car, *tmp1;
462         struct hsm_agent                *ha, *tmp2;
463         struct cdt_restore_handle       *crh, *tmp3;
464         struct mdt_thread_info          *cdt_mti;
465
466         /* start cleaning */
467         down_write(&cdt->cdt_request_lock);
468         list_for_each_entry_safe(car, tmp1, &cdt->cdt_request_list,
469                                  car_request_list) {
470                 cfs_hash_del(cdt->cdt_request_cookie_hash,
471                              &car->car_hai->hai_cookie,
472                              &car->car_cookie_hash);
473                 list_del(&car->car_request_list);
474                 mdt_cdt_put_request(car);
475         }
476         up_write(&cdt->cdt_request_lock);
477
478         down_write(&cdt->cdt_agent_lock);
479         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
480                 list_del(&ha->ha_list);
481                 if (ha->ha_archive_cnt != 0)
482                         OBD_FREE_PTR_ARRAY(ha->ha_archive_id,
483                                            ha->ha_archive_cnt);
484                 OBD_FREE_PTR(ha);
485         }
486         up_write(&cdt->cdt_agent_lock);
487
488         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
489         mutex_lock(&cdt->cdt_restore_lock);
490         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_handle_list,
491                                  crh_list) {
492                 /* not locked yet, cleanup by cdt_restore_handle_add() */
493                 if (crh->crh_lh.mlh_type == MDT_NUL_LOCK)
494                         continue;
495                 list_del(&crh->crh_list);
496                 /* give back layout lock */
497                 mdt_object_unlock(cdt_mti, NULL, &crh->crh_lh, 1);
498                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
499         }
500         mutex_unlock(&cdt->cdt_restore_lock);
501 }
502
503 /*
504  * Coordinator state transition table, indexed on enum cdt_states, taking
505  * from and to states. For instance since CDT_INIT to CDT_RUNNING is a
506  * valid transition, cdt_transition[CDT_INIT][CDT_RUNNING] is true.
507  */
508 static bool cdt_transition[CDT_STATES_COUNT][CDT_STATES_COUNT] = {
509         /* from -> to:    stopped init   running disable stopping */
510         /* stopped */   { true,   true,  false,  false,  false },
511         /* init */      { true,   false, true,   false,  false },
512         /* running */   { false,  false, true,   true,   true },
513         /* disable */   { false,  false, true,   true,   true },
514         /* stopping */  { true,   false, false,  false,  false }
515 };
516
517 /**
518  * Change coordinator thread state
519  * Some combinations are not valid, so catch them here.
520  *
521  * Returns 0 on success, with old_state set if not NULL, or -EINVAL if
522  * the transition was not possible.
523  */
524 static int set_cdt_state_locked(struct coordinator *cdt,
525                                 enum cdt_states new_state)
526 {
527         int rc;
528         enum cdt_states state;
529
530         state = cdt->cdt_state;
531
532         if (cdt_transition[state][new_state]) {
533                 cdt->cdt_state = new_state;
534                 rc = 0;
535         } else {
536                 CDEBUG(D_HSM,
537                        "unexpected coordinator transition, from=%s, to=%s\n",
538                        cdt_mdt_state2str(state), cdt_mdt_state2str(new_state));
539                 rc = -EINVAL;
540         }
541
542         return rc;
543 }
544
545 static int set_cdt_state(struct coordinator *cdt, enum cdt_states new_state)
546 {
547         int rc;
548
549         mutex_lock(&cdt->cdt_state_lock);
550         rc = set_cdt_state_locked(cdt, new_state);
551         mutex_unlock(&cdt->cdt_state_lock);
552
553         return rc;
554 }
555
556 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti);
557
558 static void cdt_start_pending_restore(struct mdt_device *mdt,
559                                       struct coordinator *cdt)
560 {
561         struct mdt_thread_info *cdt_mti;
562         unsigned int i = 0;
563         int rc;
564
565         /* wait until MDD initialize hsm actions llog */
566         while (!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state) && i < obd_timeout) {
567                 schedule_timeout_interruptible(cfs_time_seconds(1));
568                 i++;
569         }
570         if (!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state))
571                 CWARN("%s: trying to init HSM before MDD\n", mdt_obd_name(mdt));
572
573         /* set up list of started restore requests */
574         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
575         rc = mdt_hsm_pending_restore(cdt_mti);
576         if (rc)
577                 CERROR("%s: cannot take the layout locks needed for registered restore: %d\n",
578                        mdt_obd_name(mdt), rc);
579
580 }
581
582 /**
583  * coordinator thread
584  * \param data [IN] obd device
585  * \retval 0 success
586  * \retval -ve failure
587  */
588 static int mdt_coordinator(void *data)
589 {
590         struct mdt_thread_info  *mti = data;
591         struct mdt_device       *mdt = mti->mti_mdt;
592         struct coordinator      *cdt = &mdt->mdt_coordinator;
593         struct hsm_scan_data     hsd = { NULL };
594         time64_t                 last_housekeeping = 0;
595         size_t request_sz = 0;
596         int rc;
597         ENTRY;
598
599         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
600                mdt_obd_name(mdt), current->pid);
601
602         hsd.hsd_mti = mti;
603         obd_uuid2fsname(hsd.hsd_fsname, mdt_obd_name(mdt),
604                         sizeof(hsd.hsd_fsname));
605
606         set_cdt_state(cdt, CDT_RUNNING);
607
608         /* Inform mdt_hsm_cdt_start(). */
609         wake_up(&cdt->cdt_waitq);
610         cdt_start_pending_restore(mdt, cdt);
611
612         while (1) {
613                 int i;
614                 int update_idx = 0;
615                 int updates_sz;
616                 int updates_cnt;
617                 u32 start_cat_idx;
618                 u32 start_rec_idx;
619                 struct hsm_record_update *updates;
620
621                 /* Limit execution of the expensive requests traversal
622                  * to at most one second. This prevents repeatedly
623                  * locking/unlocking the catalog for each request
624                  * and preventing other HSM operations from happening
625                  */
626                 wait_event_interruptible_timeout(cdt->cdt_waitq,
627                                                  kthread_should_stop() ||
628                                                  cdt->cdt_wakeup_coordinator,
629                                                  cfs_time_seconds(1));
630
631                 cdt->cdt_wakeup_coordinator = false;
632                 CDEBUG(D_HSM, "coordinator resumes\n");
633
634                 if (kthread_should_stop()) {
635                         CDEBUG(D_HSM, "Coordinator stops\n");
636                         rc = 0;
637                         break;
638                 }
639
640                 /* if coordinator is suspended continue to wait */
641                 if (cdt->cdt_state == CDT_DISABLE) {
642                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
643                         continue;
644                 }
645
646                 /* If no event, and no housekeeping to do, continue to
647                  * wait. */
648                 if (last_housekeeping + cdt->cdt_loop_period <=
649                     ktime_get_real_seconds()) {
650                         last_housekeeping = ktime_get_real_seconds();
651                         hsd.hsd_housekeeping = true;
652                         start_cat_idx = 0;
653                         start_rec_idx = 0;
654                 } else if (cdt->cdt_event) {
655                         hsd.hsd_housekeeping = false;
656                         start_cat_idx = hsd.hsd_start_cat_idx;
657                         start_rec_idx = hsd.hsd_start_rec_idx;
658                 } else {
659                         continue;
660                 }
661
662                 cdt->cdt_event = false;
663
664                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
665
666                 if (hsd.hsd_request_len != cdt->cdt_max_requests) {
667                         /* cdt_max_requests has changed,
668                          * we need to allocate a new buffer
669                          */
670                         struct hsm_scan_request *tmp = NULL;
671                         int max_requests = cdt->cdt_max_requests;
672                         OBD_ALLOC_LARGE(tmp, max_requests *
673                                         sizeof(struct hsm_scan_request));
674                         if (!tmp) {
675                                 CERROR("Failed to resize request buffer, "
676                                        "keeping it at %d\n",
677                                        hsd.hsd_request_len);
678                         } else {
679                                 if (hsd.hsd_request != NULL)
680                                         OBD_FREE_LARGE(hsd.hsd_request,
681                                                        request_sz);
682
683                                 hsd.hsd_request_len = max_requests;
684                                 request_sz = hsd.hsd_request_len *
685                                         sizeof(struct hsm_scan_request);
686                                 hsd.hsd_request = tmp;
687                         }
688                 }
689
690                 hsd.hsd_action_count = 0;
691                 hsd.hsd_request_count = 0;
692                 hsd.hsd_one_restore = false;
693
694                 rc = cdt_llog_process(mti->mti_env, mdt, mdt_coordinator_cb,
695                                       &hsd, start_cat_idx, start_rec_idx,
696                                       WRITE);
697                 if (rc < 0)
698                         goto clean_cb_alloc;
699
700                 CDEBUG(D_HSM, "found %d requests to send\n",
701                        hsd.hsd_request_count);
702
703                 if (list_empty(&cdt->cdt_agents)) {
704                         CDEBUG(D_HSM, "no agent available, "
705                                       "coordinator sleeps\n");
706                         /* reset HSM scanning index range. */
707                         hsd.hsd_start_cat_idx = start_cat_idx;
708                         hsd.hsd_start_rec_idx = start_rec_idx;
709                         goto clean_cb_alloc;
710                 }
711
712                 /* Compute how many HAI we have in all the requests */
713                 updates_cnt = 0;
714                 for (i = 0; i < hsd.hsd_request_count; i++) {
715                         const struct hsm_scan_request *request =
716                                 &hsd.hsd_request[i];
717
718                         updates_cnt += request->hal->hal_count;
719                 }
720
721                 /* Allocate a temporary array to store the cookies to
722                  * update, and their status. */
723                 updates_sz = updates_cnt * sizeof(*updates);
724                 OBD_ALLOC_LARGE(updates, updates_sz);
725                 if (updates == NULL) {
726                         CERROR("%s: Cannot allocate memory (%d bytes) "
727                                "for %d updates. Too many HSM requests?\n",
728                                mdt_obd_name(mdt), updates_sz, updates_cnt);
729                         goto clean_cb_alloc;
730                 }
731
732                 /* here hsd contains a list of requests to be started */
733                 for (i = 0; i < hsd.hsd_request_count; i++) {
734                         struct hsm_scan_request *request = &hsd.hsd_request[i];
735                         struct hsm_action_list  *hal = request->hal;
736                         struct hsm_action_item  *hai;
737                         int                      j;
738
739                         /* still room for work ? */
740                         if (atomic_read(&cdt->cdt_request_count) >=
741                             cdt->cdt_max_requests)
742                                 break;
743
744                         rc = mdt_hsm_agent_send(mti, hal, 0);
745                         /* if failure, we suppose it is temporary
746                          * if the copy tool failed to do the request
747                          * it has to use hsm_progress
748                          */
749
750                         /* set up cookie vector to set records status
751                          * after copy tools start or failed
752                          */
753                         hai = hai_first(hal);
754                         for (j = 0; j < hal->hal_count; j++) {
755                                 updates[update_idx].cookie = hai->hai_cookie;
756                                 updates[update_idx].status =
757                                         (rc ? ARS_WAITING : ARS_STARTED);
758                                 hai = hai_next(hai);
759                                 update_idx++;
760                         }
761
762                         /* TODO: narrow down the HSM action range that already
763                          * scanned accroding to the cookies when a failure
764                          * occurs.
765                          */
766                         if (rc) {
767                                 hsd.hsd_start_cat_idx = start_cat_idx;
768                                 hsd.hsd_start_rec_idx = start_rec_idx;
769                         }
770                 }
771
772                 if (update_idx) {
773                         rc = mdt_agent_record_update(mti, updates, update_idx);
774                         if (rc)
775                                 CERROR("%s: mdt_agent_record_update() failed, "
776                                        "rc=%d, cannot update records "
777                                        "for %d cookies\n",
778                                        mdt_obd_name(mdt), rc, update_idx);
779                 }
780
781                 OBD_FREE_LARGE(updates, updates_sz);
782
783 clean_cb_alloc:
784                 /* free hal allocated by callback */
785                 for (i = 0; i < hsd.hsd_request_count; i++) {
786                         struct hsm_scan_request *request = &hsd.hsd_request[i];
787
788                         OBD_FREE_LARGE(request->hal, request->hal_sz);
789                 }
790         }
791
792         if (hsd.hsd_request != NULL)
793                 OBD_FREE_LARGE(hsd.hsd_request, request_sz);
794
795         mdt_hsm_cdt_cleanup(mdt);
796
797         if (rc != 0)
798                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
799                        mdt_obd_name(mdt), current->pid, rc);
800         else
801                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
802                               " no error\n",
803                        mdt_obd_name(mdt), current->pid);
804
805         RETURN(rc);
806 }
807
808 /**
809  * register a new HSM restore handle for a file and take EX lock on the layout
810  * \param mti [IN] thread info
811  * \param cdt [IN] coordinator
812  * \param fid [IN] fid of the file to restore
813  * \param he  [IN] HSM extent
814  * \retval 0 success
815  * \retval 1 restore handle already exists for the fid
816  * \retval -ve failure
817  */
818 int cdt_restore_handle_add(struct mdt_thread_info *mti, struct coordinator *cdt,
819                            const struct lu_fid *fid,
820                            const struct hsm_extent *he)
821 {
822         struct mdt_lock_handle lh = { 0 };
823         struct cdt_restore_handle *crh;
824         struct mdt_object *obj;
825         int rc;
826         ENTRY;
827
828         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
829         if (crh == NULL)
830                 RETURN(-ENOMEM);
831
832         crh->crh_fid = *fid;
833         /* in V1 all file is restored
834          * crh->extent.start = he->offset;
835          * crh->extent.end = he->offset + he->length;
836          */
837         crh->crh_extent.start = 0;
838         crh->crh_extent.end = he->length;
839         crh->crh_lh.mlh_type = MDT_NUL_LOCK;
840
841         mutex_lock(&cdt->cdt_restore_lock);
842         if (cdt_restore_handle_find(cdt, fid) != NULL)
843                 GOTO(out_crl, rc = 1);
844
845         if (unlikely(cdt->cdt_state == CDT_STOPPED ||
846                      cdt->cdt_state == CDT_STOPPING))
847                 GOTO(out_crl, rc = -EAGAIN);
848
849         list_add_tail(&crh->crh_list, &cdt->cdt_restore_handle_list);
850         mutex_unlock(&cdt->cdt_restore_lock);
851
852         /* get the layout lock */
853         mdt_lock_reg_init(&lh, LCK_EX);
854         obj = mdt_object_find_lock(mti, &crh->crh_fid, &lh,
855                                    MDS_INODELOCK_LAYOUT);
856         if (IS_ERR(obj)) {
857                 mutex_lock(&cdt->cdt_restore_lock);
858                 GOTO(out_ldel, rc = PTR_ERR(obj));
859         }
860
861         /* We do not keep a reference on the object during the restore
862          * which can be very long.
863          */
864         mdt_object_put(mti->mti_env, obj);
865
866         mutex_lock(&cdt->cdt_restore_lock);
867         if (unlikely(cdt->cdt_state == CDT_STOPPED ||
868                      cdt->cdt_state == CDT_STOPPING))
869                 GOTO(out_lh, rc = -EAGAIN);
870
871         crh->crh_lh = lh;
872         mutex_unlock(&cdt->cdt_restore_lock);
873
874         RETURN(0);
875 out_lh:
876         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
877 out_ldel:
878         list_del(&crh->crh_list);
879 out_crl:
880         mutex_unlock(&cdt->cdt_restore_lock);
881         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
882
883         return rc;
884 }
885
886 /**
887  * lookup a restore handle by FID
888  * caller needs to hold cdt_restore_lock
889  * \param cdt [IN] coordinator
890  * \param fid [IN] FID
891  * \retval cdt_restore_handle found
892  * \retval NULL not found
893  */
894 struct cdt_restore_handle *cdt_restore_handle_find(struct coordinator *cdt,
895                                                    const struct lu_fid *fid)
896 {
897         struct cdt_restore_handle *crh;
898         ENTRY;
899
900         list_for_each_entry(crh, &cdt->cdt_restore_handle_list, crh_list) {
901                 if (lu_fid_eq(&crh->crh_fid, fid))
902                         RETURN(crh);
903         }
904
905         RETURN(NULL);
906 }
907
908 void cdt_restore_handle_del(struct mdt_thread_info *mti,
909                             struct coordinator *cdt, const struct lu_fid *fid)
910 {
911         struct cdt_restore_handle *crh;
912
913         /* give back layout lock */
914         mutex_lock(&cdt->cdt_restore_lock);
915         crh = cdt_restore_handle_find(cdt, fid);
916         if (crh != NULL)
917                 list_del(&crh->crh_list);
918         mutex_unlock(&cdt->cdt_restore_lock);
919
920         if (crh == NULL)
921                 return;
922
923         /* XXX We pass a NULL object since the restore handle does not
924          * keep a reference on the object being restored. */
925         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
926         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
927 }
928
929 /**
930  * data passed to llog_cat_process() callback
931  * to scan requests and take actions
932  */
933 struct hsm_restore_data {
934         struct mdt_thread_info  *hrd_mti;
935 };
936
937 /**
938  *  llog_cat_process() callback, used to:
939  *  - find restore request and allocate the restore handle
940  * \param env [IN] environment
941  * \param llh [IN] llog handle
942  * \param hdr [IN] llog record
943  * \param data [IN/OUT] cb data = struct hsm_restore_data
944  * \retval 0 success
945  * \retval -ve failure
946  */
947 static int hsm_restore_cb(const struct lu_env *env,
948                           struct llog_handle *llh,
949                           struct llog_rec_hdr *hdr, void *data)
950 {
951         struct llog_agent_req_rec       *larr;
952         struct hsm_restore_data         *hrd;
953         struct hsm_action_item          *hai;
954         struct mdt_thread_info          *mti;
955         struct coordinator              *cdt;
956         int rc;
957         ENTRY;
958
959         hrd = data;
960         mti = hrd->hrd_mti;
961         cdt = &mti->mti_mdt->mdt_coordinator;
962
963         larr = (struct llog_agent_req_rec *)hdr;
964         hai = &larr->arr_hai;
965         if (hai->hai_cookie >= cdt->cdt_last_cookie) {
966                 /* update the cookie to avoid collision */
967                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
968         }
969
970         if (hai->hai_action != HSMA_RESTORE ||
971             agent_req_in_final_state(larr->arr_status))
972                 RETURN(0);
973
974         /* restore request not in a final state */
975
976         /* force replay of restore requests left in started state from previous
977          * CDT context, to be canceled later if finally found to be incompatible
978          * when being re-started */
979         if (larr->arr_status == ARS_STARTED) {
980                 larr->arr_status = ARS_WAITING;
981                 larr->arr_req_change = ktime_get_real_seconds();
982                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
983                 if (rc != 0)
984                         GOTO(out, rc);
985         }
986
987         rc = cdt_restore_handle_add(mti, cdt, &hai->hai_fid, &hai->hai_extent);
988         if (rc == 1)
989                 rc = 0;
990 out:
991         RETURN(rc);
992 }
993
994 /**
995  * restore coordinator state at startup
996  * the goal is to take a layout lock for each registered restore request
997  * \param mti [IN] context
998  */
999 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
1000 {
1001         struct hsm_restore_data  hrd;
1002         int                      rc;
1003         ENTRY;
1004
1005         hrd.hrd_mti = mti;
1006
1007         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, hsm_restore_cb, &hrd,
1008                               0, 0, WRITE);
1009
1010         RETURN(rc);
1011 }
1012
1013 int hsm_init_ucred(struct lu_ucred *uc)
1014 {
1015         ENTRY;
1016         uc->uc_valid = UCRED_OLD;
1017         uc->uc_o_uid = 0;
1018         uc->uc_o_gid = 0;
1019         uc->uc_o_fsuid = 0;
1020         uc->uc_o_fsgid = 0;
1021         uc->uc_uid = 0;
1022         uc->uc_gid = 0;
1023         uc->uc_fsuid = 0;
1024         uc->uc_fsgid = 0;
1025         uc->uc_suppgids[0] = -1;
1026         uc->uc_suppgids[1] = -1;
1027         uc->uc_cap = cap_combine(CAP_FS_SET, CAP_NFSD_SET);
1028         uc->uc_umask = 0777;
1029         uc->uc_ginfo = NULL;
1030         uc->uc_identity = NULL;
1031         /* always record internal HSM activity if also enabled globally */
1032         uc->uc_enable_audit = 1;
1033         /* do not let rbac interfere with HSM internal processing */
1034         uc->uc_rbac_file_perms = 1;
1035         uc->uc_rbac_dne_ops = 1;
1036         uc->uc_rbac_quota_ops = 1;
1037         uc->uc_rbac_byfid_ops = 1;
1038         uc->uc_rbac_chlg_ops = 1;
1039         uc->uc_rbac_fscrypt_admin = 1;
1040
1041         RETURN(0);
1042 }
1043
1044 /**
1045  * initialize coordinator struct
1046  * \param mdt [IN] device
1047  * \retval 0 success
1048  * \retval -ve failure
1049  */
1050 int mdt_hsm_cdt_init(struct mdt_device *mdt)
1051 {
1052         struct coordinator      *cdt = &mdt->mdt_coordinator;
1053         struct mdt_thread_info  *cdt_mti = NULL;
1054         int                      rc;
1055         ENTRY;
1056
1057         init_waitqueue_head(&cdt->cdt_waitq);
1058         init_rwsem(&cdt->cdt_llog_lock);
1059         init_rwsem(&cdt->cdt_agent_lock);
1060         init_rwsem(&cdt->cdt_request_lock);
1061         mutex_init(&cdt->cdt_restore_lock);
1062         mutex_init(&cdt->cdt_state_lock);
1063         set_cdt_state(cdt, CDT_STOPPED);
1064
1065         INIT_LIST_HEAD(&cdt->cdt_request_list);
1066         INIT_LIST_HEAD(&cdt->cdt_agents);
1067         INIT_LIST_HEAD(&cdt->cdt_restore_handle_list);
1068
1069         cdt->cdt_request_cookie_hash = cfs_hash_create("REQUEST_COOKIE_HASH",
1070                                                        CFS_HASH_BITS_MIN,
1071                                                        CFS_HASH_BITS_MAX,
1072                                                        CFS_HASH_BKT_BITS,
1073                                                        0 /* extra bytes */,
1074                                                        CFS_HASH_MIN_THETA,
1075                                                        CFS_HASH_MAX_THETA,
1076                                                 &cdt_request_cookie_hash_ops,
1077                                                        CFS_HASH_DEFAULT);
1078         if (cdt->cdt_request_cookie_hash == NULL)
1079                 RETURN(-ENOMEM);
1080
1081         cdt->cdt_agent_record_hash = cfs_hash_create("AGENT_RECORD_HASH",
1082                                                      CFS_HASH_BITS_MIN,
1083                                                      CFS_HASH_BITS_MAX,
1084                                                      CFS_HASH_BKT_BITS,
1085                                                      0 /* extra bytes */,
1086                                                      CFS_HASH_MIN_THETA,
1087                                                      CFS_HASH_MAX_THETA,
1088                                                      &cdt_agent_record_hash_ops,
1089                                                      CFS_HASH_DEFAULT);
1090         if (cdt->cdt_agent_record_hash == NULL)
1091                 GOTO(out_request_cookie_hash, rc = -ENOMEM);
1092
1093         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
1094         if (rc < 0)
1095                 GOTO(out_agent_record_hash, rc);
1096
1097         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1098         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
1099         if (rc < 0)
1100                 GOTO(out_env, rc);
1101
1102         lu_context_enter(&cdt->cdt_session);
1103         cdt->cdt_env.le_ses = &cdt->cdt_session;
1104
1105         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1106         LASSERT(cdt_mti != NULL);
1107
1108         cdt_mti->mti_env = &cdt->cdt_env;
1109         cdt_mti->mti_mdt = mdt;
1110
1111         hsm_init_ucred(mdt_ucred(cdt_mti));
1112
1113         /* default values for sysfs tunnables
1114          * can be override by MGS conf */
1115         cdt->cdt_default_archive_id = 1;
1116         cdt->cdt_grace_delay = 60;
1117         cdt->cdt_loop_period = 10;
1118         cdt->cdt_max_requests = 3;
1119         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1120         cdt->cdt_active_req_timeout = 3600;
1121
1122         /* by default do not remove archives on last unlink */
1123         cdt->cdt_remove_archive_on_last_unlink = false;
1124
1125         RETURN(0);
1126
1127 out_env:
1128         lu_env_fini(&cdt->cdt_env);
1129 out_agent_record_hash:
1130         cfs_hash_putref(cdt->cdt_agent_record_hash);
1131         cdt->cdt_agent_record_hash = NULL;
1132 out_request_cookie_hash:
1133         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1134         cdt->cdt_request_cookie_hash = NULL;
1135
1136         return rc;
1137 }
1138
1139 /**
1140  * free a coordinator thread
1141  * \param mdt [IN] device
1142  */
1143 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
1144 {
1145         struct coordinator *cdt = &mdt->mdt_coordinator;
1146         ENTRY;
1147
1148         lu_context_exit(cdt->cdt_env.le_ses);
1149         lu_context_fini(cdt->cdt_env.le_ses);
1150
1151         lu_env_fini(&cdt->cdt_env);
1152
1153         cfs_hash_putref(cdt->cdt_agent_record_hash);
1154         cdt->cdt_agent_record_hash = NULL;
1155
1156         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1157         cdt->cdt_request_cookie_hash = NULL;
1158
1159         RETURN(0);
1160 }
1161
1162 /**
1163  * start a coordinator thread
1164  * \param mdt [IN] device
1165  * \retval 0 success
1166  * \retval -ve failure
1167  */
1168 static int mdt_hsm_cdt_start(struct mdt_device *mdt)
1169 {
1170         struct coordinator *cdt = &mdt->mdt_coordinator;
1171         struct mdt_thread_info *cdt_mti;
1172         int rc;
1173         void *ptr;
1174         struct task_struct *task;
1175         ENTRY;
1176
1177         /* functions defined but not yet used
1178          * this avoid compilation warning
1179          */
1180         ptr = dump_requests;
1181
1182         rc = set_cdt_state(cdt, CDT_INIT);
1183         if (rc) {
1184                 CERROR("%s: Coordinator already started or stopping\n",
1185                        mdt_obd_name(mdt));
1186                 RETURN(-EALREADY);
1187         }
1188
1189         BUILD_BUG_ON(BIT(CDT_POLICY_SHIFT_COUNT - 1) != CDT_POLICY_LAST);
1190         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1191
1192         /* just need to be larger than previous one */
1193         /* cdt_last_cookie is protected by cdt_llog_lock */
1194         cdt->cdt_last_cookie = ktime_get_real_seconds();
1195         atomic_set(&cdt->cdt_request_count, 0);
1196         atomic_set(&cdt->cdt_archive_count, 0);
1197         atomic_set(&cdt->cdt_restore_count, 0);
1198         atomic_set(&cdt->cdt_remove_count, 0);
1199         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
1200         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
1201         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
1202
1203         /* to avoid deadlock when start is made through sysfs
1204          * sysfs entries are created by the coordinator thread
1205          */
1206         if (mdt->mdt_bottom->dd_rdonly)
1207                 RETURN(0);
1208
1209         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1210         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
1211         if (IS_ERR(task)) {
1212                 rc = PTR_ERR(task);
1213                 set_cdt_state(cdt, CDT_STOPPED);
1214                 CERROR("%s: error starting coordinator thread: %d\n",
1215                        mdt_obd_name(mdt), rc);
1216         } else {
1217                 cdt->cdt_task = task;
1218                 wait_event(cdt->cdt_waitq,
1219                            cdt->cdt_state != CDT_INIT);
1220                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
1221                        mdt_obd_name(mdt));
1222                 rc = 0;
1223         }
1224
1225         RETURN(rc);
1226 }
1227
1228 /**
1229  * stop a coordinator thread
1230  * \param mdt [IN] device
1231  */
1232 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
1233 {
1234         struct coordinator *cdt = &mdt->mdt_coordinator;
1235         int rc;
1236
1237         ENTRY;
1238         /* stop coordinator thread */
1239         rc = set_cdt_state(cdt, CDT_STOPPING);
1240         if (rc == 0) {
1241                 kthread_stop(cdt->cdt_task);
1242                 cdt->cdt_task = NULL;
1243                 set_cdt_state(cdt, CDT_STOPPED);
1244         }
1245
1246         RETURN(rc);
1247 }
1248
1249 static int mdt_hsm_set_exists(struct mdt_thread_info *mti,
1250                               const struct lu_fid *fid,
1251                               u32 archive_id)
1252 {
1253         struct mdt_object *obj;
1254         struct md_hsm mh;
1255         int rc;
1256
1257         obj = mdt_hsm_get_md_hsm(mti, fid, &mh);
1258         if (IS_ERR(obj))
1259                 GOTO(out, rc = PTR_ERR(obj));
1260
1261         if (mh.mh_flags & HS_EXISTS &&
1262             mh.mh_arch_id == archive_id)
1263                 GOTO(out_obj, rc = 0);
1264
1265         mh.mh_flags |= HS_EXISTS;
1266         mh.mh_arch_id = archive_id;
1267         rc = mdt_hsm_attr_set(mti, obj, &mh);
1268
1269 out_obj:
1270         mdt_object_put(mti->mti_env, obj);
1271 out:
1272         return rc;
1273 }
1274
1275 /**
1276  * register all requests from an hal in the memory list
1277  * \param mti [IN] context
1278  * \param hal [IN] request
1279  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1280  *  which is running the CT
1281  * \retval 0 success
1282  * \retval -ve failure
1283  */
1284 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1285                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1286 {
1287         struct mdt_device       *mdt = mti->mti_mdt;
1288         struct coordinator      *cdt = &mdt->mdt_coordinator;
1289         struct hsm_action_item  *hai;
1290         int                      rc = 0, i;
1291         ENTRY;
1292
1293         /* register request in memory list */
1294         hai = hai_first(hal);
1295         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1296                 struct cdt_agent_req *car;
1297
1298                 /* in case of a cancel request, we first mark the ondisk
1299                  * record of the request we want to stop as canceled
1300                  * this does not change the cancel record
1301                  * it will be done when updating the request status
1302                  */
1303                 if (hai->hai_action == HSMA_CANCEL) {
1304                         struct hsm_record_update update = {
1305                                 .cookie = hai->hai_cookie,
1306                                 .status = ARS_CANCELED,
1307                         };
1308
1309                         rc = mdt_agent_record_update(mti, &update, 1);
1310                         if (rc) {
1311                                 CERROR("%s: mdt_agent_record_update() failed, "
1312                                        "rc=%d, cannot update status to %s "
1313                                        "for cookie %#llx\n",
1314                                        mdt_obd_name(mdt), rc,
1315                                        agent_req_status2name(ARS_CANCELED),
1316                                        hai->hai_cookie);
1317                                 GOTO(out, rc);
1318                         }
1319
1320                         /* find the running request to set it canceled */
1321                         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
1322                         if (car != NULL) {
1323                                 car->car_canceled = 1;
1324                                 /* uuid has to be changed to the one running the
1325                                 * request to cancel */
1326                                 *uuid = car->car_uuid;
1327                                 mdt_cdt_put_request(car);
1328                         }
1329                         /* no need to memorize cancel request
1330                          * this also avoid a deadlock when we receive
1331                          * a purge all requests command
1332                          */
1333                         continue;
1334                 }
1335
1336                 if (hai->hai_action == HSMA_ARCHIVE) {
1337                         rc = mdt_hsm_set_exists(mti, &hai->hai_fid,
1338                                                 hal->hal_archive_id);
1339                         if (rc == -ENOENT)
1340                                 continue;
1341                         else if (rc < 0)
1342                                 GOTO(out, rc);
1343                 }
1344
1345                 car = mdt_cdt_alloc_request(hal->hal_archive_id, hal->hal_flags,
1346                                             uuid, hai);
1347                 if (IS_ERR(car))
1348                         GOTO(out, rc = PTR_ERR(car));
1349
1350                 rc = mdt_cdt_add_request(cdt, car);
1351                 if (rc != 0)
1352                         mdt_cdt_free_request(car);
1353         }
1354 out:
1355         RETURN(rc);
1356 }
1357
1358 /**
1359  * swap layouts between 2 fids
1360  * \param mti [IN] context
1361  * \param obj [IN]
1362  * \param dfid [IN]
1363  * \param mh_common [IN] MD HSM
1364  */
1365 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1366                             struct mdt_object *obj, const struct lu_fid *dfid,
1367                             struct md_hsm *mh_common)
1368 {
1369         struct mdt_object       *dobj;
1370         struct mdt_lock_handle  *dlh;
1371         int                      rc;
1372         ENTRY;
1373
1374         if (!mdt_object_exists(obj))
1375                 GOTO(out, rc = -ENOENT);
1376
1377         /* we already have layout lock on obj so take only
1378          * on dfid */
1379         dlh = &mti->mti_lh[MDT_LH_OLD];
1380         mdt_lock_reg_init(dlh, LCK_EX);
1381         dobj = mdt_object_find_lock(mti, dfid, dlh, MDS_INODELOCK_LAYOUT);
1382         if (IS_ERR(dobj))
1383                 GOTO(out, rc = PTR_ERR(dobj));
1384
1385         /* if copy tool closes the volatile before sending the final
1386          * progress through llapi_hsm_copy_end(), all the objects
1387          * are removed and mdd_swap_layout LBUG */
1388         if (!mdt_object_exists(dobj)) {
1389                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1390                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1391                 GOTO(out_dobj, rc = -ENOENT);
1392         }
1393         /* Since we only handle restores here, unconditionally use
1394          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1395          * be preserved in case of failure during swap_layout and not
1396          * leave a file in an intermediate but incoherent state.
1397          * But need to setup HSM xattr of data FID before, reuse
1398          * mti and mh presets for FID in hsm_cdt_request_completed(),
1399          * only need to clear RELEASED and DIRTY.
1400          */
1401         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1402         rc = mdt_hsm_attr_set(mti, dobj, mh_common);
1403         if (rc == 0)
1404                 rc = mo_swap_layouts(mti->mti_env,
1405                                      mdt_object_child(obj),
1406                                      mdt_object_child(dobj),
1407                                      SWAP_LAYOUTS_MDS_HSM);
1408         if (rc == 0) {
1409                 rc = mdt_lsom_downgrade(mti, obj);
1410                 if (rc)
1411                         CDEBUG(D_INODE,
1412                                "%s: File fid="DFID" SOM "
1413                                "downgrade failed, rc = %d\n",
1414                                mdt_obd_name(mti->mti_mdt),
1415                                PFID(mdt_object_fid(obj)), rc);
1416         }
1417 out_dobj:
1418         mdt_object_unlock_put(mti, dobj, dlh, 1);
1419 out:
1420         RETURN(rc);
1421 }
1422
1423 /**
1424  * update status of a completed request
1425  * \param mti [IN] context
1426  * \param pgs [IN] progress of the copy tool
1427  * \retval 0 success
1428  * \retval -ve failure
1429  */
1430 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1431                                      struct hsm_progress_kernel *pgs,
1432                                      const struct cdt_agent_req *car,
1433                                      enum agent_req_status *status)
1434 {
1435         const struct lu_env *env = mti->mti_env;
1436         struct mdt_device *mdt = mti->mti_mdt;
1437         struct coordinator *cdt = &mdt->mdt_coordinator;
1438         struct mdt_object *obj = NULL;
1439         enum changelog_rec_flags clf_flags = 0;
1440         struct md_hsm mh;
1441         bool is_mh_changed;
1442         bool need_changelog = true;
1443         int rc = 0;
1444
1445         ENTRY;
1446         /* default is to retry */
1447         *status = ARS_WAITING;
1448
1449         /* find object by FID, mdt_hsm_get_md_hsm() returns obj or err
1450          * if error/removed continue anyway to get correct reporting done */
1451         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1452         /* we will update MD HSM only if needed */
1453         is_mh_changed = false;
1454
1455         /* no need to change mh->mh_arch_id
1456          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1457          */
1458         if (pgs->hpk_errval != 0) {
1459                 switch (pgs->hpk_errval) {
1460                 case ENOSYS:
1461                         /* the copy tool does not support cancel
1462                          * so the cancel request is failed
1463                          * As we cannot distinguish a cancel progress
1464                          * from another action progress (they have the
1465                          * same cookie), we suppose here the CT returns
1466                          * ENOSYS only if does not support cancel
1467                          */
1468                         /* this can also happen when cdt calls it to
1469                          * for a timed out request */
1470                         *status = ARS_FAILED;
1471                         /* to have a cancel event in changelog */
1472                         pgs->hpk_errval = ECANCELED;
1473                         break;
1474                 case ECANCELED:
1475                         /* the request record has already been set to
1476                          * ARS_CANCELED, this set the cancel request
1477                          * to ARS_SUCCEED */
1478                         *status = ARS_SUCCEED;
1479                         break;
1480                 default:
1481                         /* retry only if current policy or requested, and
1482                          * object is not on error/removed */
1483                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1484                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ||
1485                                    IS_ERR(obj)) ? ARS_FAILED : ARS_WAITING;
1486                         break;
1487                 }
1488
1489                 rc = hsm_set_cl_error(&clf_flags, pgs->hpk_errval);
1490                 if (rc == -EOVERFLOW) {
1491                         CERROR("%s: Request %#llx on "DFID" failed, error code %d too large\n",
1492                                mdt_obd_name(mdt), pgs->hpk_cookie,
1493                                PFID(&pgs->hpk_fid), (int)abs(pgs->hpk_errval));
1494                         rc = 0;
1495                 }
1496
1497                 switch (car->car_hai->hai_action) {
1498                 case HSMA_ARCHIVE:
1499                         hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
1500                         break;
1501                 case HSMA_RESTORE:
1502                         hsm_set_cl_event(&clf_flags, HE_RESTORE);
1503                         break;
1504                 case HSMA_REMOVE:
1505                         hsm_set_cl_event(&clf_flags, HE_REMOVE);
1506                         break;
1507                 case HSMA_CANCEL:
1508                         hsm_set_cl_event(&clf_flags, HE_CANCEL);
1509                         CERROR("%s: Failed request %#llx on "DFID
1510                                " cannot be a CANCEL\n",
1511                                mdt_obd_name(mdt),
1512                                pgs->hpk_cookie,
1513                                PFID(&pgs->hpk_fid));
1514                         break;
1515                 default:
1516                         CERROR("%s: Failed request %#llx on "DFID
1517                                " %d is an unknown action\n",
1518                                mdt_obd_name(mdt),
1519                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1520                                car->car_hai->hai_action);
1521                         rc = -EINVAL;
1522                         break;
1523                 }
1524         } else {
1525                 *status = ARS_SUCCEED;
1526                 switch (car->car_hai->hai_action) {
1527                 case HSMA_ARCHIVE:
1528                         hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
1529                         /* set ARCHIVE keep EXIST and clear LOST and
1530                          * DIRTY */
1531                         mh.mh_arch_ver = pgs->hpk_data_version;
1532                         mh.mh_flags |= HS_ARCHIVED;
1533                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1534                         is_mh_changed = true;
1535                         break;
1536                 case HSMA_RESTORE:
1537                         hsm_set_cl_event(&clf_flags, HE_RESTORE);
1538
1539                         /* do not clear RELEASED and DIRTY here
1540                          * this will occur in hsm_swap_layouts()
1541                          */
1542
1543                         /* Restoring has changed the file version on
1544                          * disk. */
1545                         mh.mh_arch_ver = pgs->hpk_data_version;
1546                         is_mh_changed = true;
1547                         break;
1548                 case HSMA_REMOVE:
1549                         hsm_set_cl_event(&clf_flags, HE_REMOVE);
1550                         /* clear ARCHIVED EXISTS and LOST */
1551                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1552                         is_mh_changed = true;
1553                         break;
1554                 case HSMA_CANCEL:
1555                         hsm_set_cl_event(&clf_flags, HE_CANCEL);
1556                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1557                                mdt_obd_name(mdt),
1558                                pgs->hpk_cookie,
1559                                PFID(&pgs->hpk_fid));
1560                         break;
1561                 default:
1562                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1563                                mdt_obd_name(mdt),
1564                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1565                                car->car_hai->hai_action);
1566                         rc = -EINVAL;
1567                         break;
1568                 }
1569         }
1570
1571         /* rc != 0 means error when analysing action, it may come from
1572          * a crasy CT no need to manage DIRTY
1573          * and if mdt_hsm_get_md_hsm() has returned an error, mh has not been
1574          * filled
1575          */
1576         if (rc == 0 && !IS_ERR(obj))
1577                 hsm_set_cl_flags(&clf_flags,
1578                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1579
1580         /* unlock is done later, after layout lock management */
1581         if (is_mh_changed && !IS_ERR(obj))
1582                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1583
1584         /* we give back layout lock only if restore was successful or
1585          * if no retry will be attempted and if object is still alive,
1586          * in other cases we just unlock the object */
1587         if (car->car_hai->hai_action == HSMA_RESTORE) {
1588                 struct mdt_lock_handle *lh;
1589
1590                 /* restore in data FID done, we swap the layouts
1591                  * only if restore is successful */
1592                 if (pgs->hpk_errval == 0 && !IS_ERR(obj)) {
1593                         rc = hsm_swap_layouts(mti, obj, &car->car_hai->hai_dfid,
1594                                               &mh);
1595                         if (rc) {
1596                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1597                                         *status = ARS_FAILED;
1598                                 pgs->hpk_errval = -rc;
1599                                 hsm_set_cl_error(&clf_flags, pgs->hpk_errval);
1600                         }
1601                 }
1602                 /* we have to retry, so keep layout lock */
1603                 if (*status == ARS_WAITING)
1604                         GOTO(out, rc);
1605
1606                 /* restore special case, need to create ChangeLog record
1607                  * before to give back layout lock to avoid concurrent
1608                  * file updater to post out of order ChangeLog */
1609                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
1610                              &car->car_hai->hai_fid);
1611                 need_changelog = false;
1612
1613                 cdt_restore_handle_del(mti, cdt, &car->car_hai->hai_fid);
1614                 if (!IS_ERR_OR_NULL(obj)) {
1615                         /* flush UPDATE lock so attributes are upadated */
1616                         lh = &mti->mti_lh[MDT_LH_OLD];
1617                         mdt_lock_reg_init(lh, LCK_EX);
1618                         mdt_object_lock(mti, obj, lh, MDS_INODELOCK_UPDATE);
1619                         mdt_object_unlock(mti, obj, lh, 1);
1620                 }
1621         }
1622
1623         GOTO(out, rc);
1624
1625 out:
1626         /* always add a ChangeLog record */
1627         if (need_changelog)
1628                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
1629                              &car->car_hai->hai_fid);
1630
1631         if (!IS_ERR(obj))
1632                 mdt_object_put(mti->mti_env, obj);
1633
1634         RETURN(rc);
1635 }
1636
1637 /**
1638  * update status of a request
1639  * \param mti [IN] context
1640  * \param pgs [IN] progress of the copy tool
1641  * \retval 0 success
1642  * \retval -ve failure
1643  */
1644 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1645                                  struct hsm_progress_kernel *pgs)
1646 {
1647         struct mdt_device       *mdt = mti->mti_mdt;
1648         struct coordinator      *cdt = &mdt->mdt_coordinator;
1649         struct cdt_agent_req    *car;
1650         int                      rc = 0;
1651         ENTRY;
1652
1653         /* no coordinator started, so we cannot serve requests */
1654         if (cdt->cdt_state == CDT_STOPPED)
1655                 RETURN(-EAGAIN);
1656
1657         /* first do sanity checks */
1658         car = mdt_cdt_update_request(cdt, pgs);
1659         if (IS_ERR(car)) {
1660                 CERROR("%s: Cannot find running request for cookie %#llx"
1661                        " on fid="DFID"\n",
1662                        mdt_obd_name(mdt),
1663                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1664
1665                 RETURN(PTR_ERR(car));
1666         }
1667
1668         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1669                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1670                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1671                       hsm_copytool_action2name(car->car_hai->hai_action),
1672                       pgs->hpk_flags, pgs->hpk_errval,
1673                       PFID(&car->car_hai->hai_fid),
1674                       PFID(&car->car_hai->hai_dfid));
1675
1676         /* progress is done on FID or data FID depending of the action and
1677          * of the copy progress */
1678         /* for restore progress is used to send back the data FID to cdt */
1679         if (car->car_hai->hai_action == HSMA_RESTORE &&
1680             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1681                 car->car_hai->hai_dfid = pgs->hpk_fid;
1682
1683         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1684              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1685             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1686              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1687                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1688                        " does not match request FID "DFID" nor data FID "
1689                        DFID"\n",
1690                        mdt_obd_name(mdt),
1691                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1692                        PFID(&car->car_hai->hai_fid),
1693                        PFID(&car->car_hai->hai_dfid));
1694                 GOTO(out, rc = -EINVAL);
1695         }
1696
1697         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1698                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1699                        " is not coherent (err=%d and not completed"
1700                        " (flags=%d))\n",
1701                        mdt_obd_name(mdt),
1702                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1703                        hsm_copytool_action2name(car->car_hai->hai_action),
1704                        pgs->hpk_errval, pgs->hpk_flags);
1705                 GOTO(out, rc = -EINVAL);
1706         }
1707
1708         /* now progress is valid */
1709
1710         /* we use a root like ucred */
1711         hsm_init_ucred(mdt_ucred(mti));
1712
1713         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1714                 enum agent_req_status status;
1715                 struct hsm_record_update update;
1716                 int rc1;
1717
1718                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1719
1720                 CDEBUG(D_HSM, "updating record: fid="DFID" cookie=%#llx action=%s "
1721                               "status=%s\n",
1722                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1723                        hsm_copytool_action2name(car->car_hai->hai_action),
1724                        agent_req_status2name(status));
1725
1726                 /* update record first (LU-9075) */
1727                 update.cookie = pgs->hpk_cookie;
1728                 update.status = status;
1729
1730                 rc1 = mdt_agent_record_update(mti, &update, 1);
1731                 if (rc1)
1732                         CERROR("%s: mdt_agent_record_update() failed,"
1733                                " rc=%d, cannot update status to %s"
1734                                " for cookie %#llx\n",
1735                                mdt_obd_name(mdt), rc1,
1736                                agent_req_status2name(status),
1737                                pgs->hpk_cookie);
1738                 rc = (rc != 0 ? rc : rc1);
1739
1740                 /* then remove request from memory list (LU-9075) */
1741                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1742
1743                 /* ct has completed a request, so a slot is available,
1744                  * signal the coordinator to find new work */
1745                 mdt_hsm_cdt_event(cdt);
1746         } else {
1747                 /* if copytool send a progress on a canceled request
1748                  * we inform copytool it should stop
1749                  */
1750                 if (car->car_canceled == 1)
1751                         rc = -ECANCELED;
1752         }
1753         GOTO(out, rc);
1754
1755 out:
1756         /* remove ref got from mdt_cdt_update_request() */
1757         mdt_cdt_put_request(car);
1758
1759         return rc;
1760 }
1761
1762
1763 /**
1764  *  llog_cat_process() callback, used to:
1765  *  - purge all requests
1766  * \param env [IN] environment
1767  * \param llh [IN] llog handle
1768  * \param hdr [IN] llog record
1769  * \param data [IN] cb data = struct mdt_thread_info
1770  * \retval 0 success
1771  * \retval -ve failure
1772  */
1773 static int mdt_cancel_all_cb(const struct lu_env *env,
1774                              struct llog_handle *llh,
1775                              struct llog_rec_hdr *hdr, void *data)
1776 {
1777         struct llog_agent_req_rec *larr = (struct llog_agent_req_rec *)hdr;
1778         struct hsm_action_item *hai = &larr->arr_hai;
1779         struct mdt_thread_info  *mti = data;
1780         struct coordinator *cdt = &mti->mti_mdt->mdt_coordinator;
1781         int rc;
1782         ENTRY;
1783
1784         if (larr->arr_status != ARS_WAITING &&
1785             larr->arr_status != ARS_STARTED)
1786                 RETURN(0);
1787
1788         /* Unlock the EX layout lock */
1789         if (hai->hai_action == HSMA_RESTORE)
1790                 cdt_restore_handle_del(mti, cdt, &hai->hai_fid);
1791
1792         larr->arr_status = ARS_CANCELED;
1793         larr->arr_req_change = ktime_get_real_seconds();
1794         rc = llog_write(env, llh, hdr, hdr->lrh_index);
1795         if (rc < 0) {
1796                 CERROR("%s: cannot update agent log: rc = %d\n",
1797                        mdt_obd_name(mti->mti_mdt), rc);
1798                 rc = LLOG_DEL_RECORD;
1799         }
1800
1801         RETURN(rc);
1802 }
1803
1804 /**
1805  * cancel all actions
1806  * \param obd [IN] MDT device
1807  */
1808 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1809 {
1810         struct lu_env                    env;
1811         struct lu_context                session;
1812         struct mdt_thread_info          *mti;
1813         struct coordinator              *cdt = &mdt->mdt_coordinator;
1814         struct cdt_agent_req            *car;
1815         struct hsm_action_list          *hal = NULL;
1816         struct hsm_action_item          *hai;
1817         int                              hal_sz = 0, hal_len, rc;
1818         enum cdt_states                  old_state;
1819         ENTRY;
1820
1821         rc = lu_env_init(&env, LCT_MD_THREAD);
1822         if (rc < 0)
1823                 RETURN(rc);
1824
1825         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1826         rc = lu_context_init(&session, LCT_SERVER_SESSION);
1827         if (rc < 0)
1828                 GOTO(out_env, rc);
1829
1830         lu_context_enter(&session);
1831         env.le_ses = &session;
1832
1833         mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
1834         LASSERT(mti != NULL);
1835
1836         mti->mti_env = &env;
1837         mti->mti_mdt = mdt;
1838
1839         hsm_init_ucred(mdt_ucred(mti));
1840
1841         mutex_lock(&cdt->cdt_state_lock);
1842         old_state = cdt->cdt_state;
1843
1844         /* disable coordinator */
1845         rc = set_cdt_state_locked(cdt, CDT_DISABLE);
1846         if (rc)
1847                 GOTO(out_cdt_state_unlock, rc);
1848
1849         /* send cancel to all running requests */
1850         down_read(&cdt->cdt_request_lock);
1851         list_for_each_entry(car, &cdt->cdt_request_list, car_request_list) {
1852                 mdt_cdt_get_request(car);
1853                 /* request is not yet removed from list, it will be done
1854                  * when copytool will return progress
1855                  */
1856
1857                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1858                         mdt_cdt_put_request(car);
1859                         continue;
1860                 }
1861
1862                 /* needed size */
1863                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1864                           cfs_size_round(car->car_hai->hai_len);
1865
1866                 if (hal_len > hal_sz && hal_sz > 0) {
1867                         /* not enough room, free old buffer */
1868                         OBD_FREE(hal, hal_sz);
1869                         hal = NULL;
1870                 }
1871
1872                 /* empty buffer, allocate one */
1873                 if (hal == NULL) {
1874                         hal_sz = hal_len;
1875                         OBD_ALLOC(hal, hal_sz);
1876                         if (hal == NULL) {
1877                                 mdt_cdt_put_request(car);
1878                                 up_read(&cdt->cdt_request_lock);
1879                                 GOTO(out_cdt_state, rc = -ENOMEM);
1880                         }
1881                 }
1882
1883                 hal->hal_version = HAL_VERSION;
1884                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1885                                 MTI_NAME_MAXLEN);
1886                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1887                 hal->hal_archive_id = car->car_archive_id;
1888                 hal->hal_flags = car->car_flags;
1889                 hal->hal_count = 0;
1890
1891                 hai = hai_first(hal);
1892                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1893                 hai->hai_action = HSMA_CANCEL;
1894                 hal->hal_count = 1;
1895
1896                 /* it is possible to safely call mdt_hsm_agent_send()
1897                  * (ie without a deadlock on cdt_request_lock), because the
1898                  * write lock is taken only if we are not in purge mode
1899                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1900                  *   nor mdt_cdt_remove_request())
1901                  */
1902                 /* no conflict with cdt thread because cdt is disable and we
1903                  * have the request lock */
1904                 mdt_hsm_agent_send(mti, hal, 1);
1905
1906                 mdt_cdt_put_request(car);
1907         }
1908         up_read(&cdt->cdt_request_lock);
1909
1910         if (hal != NULL)
1911                 OBD_FREE(hal, hal_sz);
1912
1913         /* cancel all on-disk records */
1914         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, mdt_cancel_all_cb,
1915                               (void *)mti, 0, 0, WRITE);
1916 out_cdt_state:
1917         /* Enable coordinator, unless the coordinator was stopping. */
1918         set_cdt_state_locked(cdt, old_state);
1919 out_cdt_state_unlock:
1920         mutex_unlock(&cdt->cdt_state_lock);
1921
1922         lu_context_exit(&session);
1923         lu_context_fini(&session);
1924 out_env:
1925         lu_env_fini(&env);
1926
1927         RETURN(rc);
1928 }
1929
1930 /**
1931  * check if a request is compatible with file status
1932  * \param hai [IN] request description
1933  * \param archive_id [IN] request archive id
1934  * \param rq_flags [IN] request flags
1935  * \param hsm [IN] file HSM metadata
1936  * \retval boolean
1937  */
1938 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1939                               u32 archive_id, u64 rq_flags,
1940                               const struct md_hsm *hsm)
1941 {
1942         int      is_compat = false;
1943         int      hsm_flags;
1944         ENTRY;
1945
1946         hsm_flags = hsm->mh_flags;
1947         switch (hai->hai_action) {
1948         case HSMA_ARCHIVE:
1949                 if (!(hsm_flags & HS_NOARCHIVE) &&
1950                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1951                         is_compat = true;
1952
1953                 if (hsm_flags & HS_EXISTS &&
1954                     archive_id != 0 &&
1955                     archive_id != hsm->mh_arch_id)
1956                         is_compat = false;
1957
1958                 break;
1959         case HSMA_RESTORE:
1960                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1961                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1962                         is_compat = true;
1963                 break;
1964         case HSMA_REMOVE:
1965                 if (!(hsm_flags & HS_RELEASED) &&
1966                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1967                         is_compat = true;
1968                 break;
1969         case HSMA_CANCEL:
1970                 is_compat = true;
1971                 break;
1972         }
1973         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
1974                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
1975                       PFID(&hai->hai_fid),
1976                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1977                       hai->hai_extent.offset, hai->hai_extent.length,
1978                       hsm->mh_flags,
1979                       (is_compat ? "compatible" : "uncompatible"));
1980
1981         RETURN(is_compat);
1982 }
1983
1984 /*
1985  * sysfs interface used to get/set HSM behaviour (cdt->cdt_policy)
1986  */
1987 static const struct {
1988         __u64            bit;
1989         char            *name;
1990         char            *nickname;
1991 } hsm_policy_names[] = {
1992         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1993         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1994         { 0 },
1995 };
1996
1997 /**
1998  * convert a policy name to a bit
1999  * \param name [IN] policy name
2000  * \retval 0 unknown
2001  * \retval   policy bit
2002  */
2003 static __u64 hsm_policy_str2bit(const char *name)
2004 {
2005         int      i;
2006
2007         for (i = 0; hsm_policy_names[i].bit != 0; i++)
2008                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
2009                     strcmp(hsm_policy_names[i].name, name) == 0)
2010                         return hsm_policy_names[i].bit;
2011         return 0;
2012 }
2013
2014 /**
2015  * convert a policy bit field to a string
2016  * \param mask [IN] policy bit field
2017  * \param hexa [IN] print mask before bit names
2018  * \param buffer [OUT] string
2019  * \param count [IN] size of buffer
2020  */
2021 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
2022                                 const bool hexa)
2023 {
2024         int      i, j;
2025         __u64    bit;
2026         ENTRY;
2027
2028         if (hexa)
2029                 seq_printf(m, "(%#llx) ", mask);
2030
2031         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
2032                 bit = (1ULL << i);
2033
2034                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
2035                         if (hsm_policy_names[j].bit == bit)
2036                                 break;
2037                 }
2038                 if (bit & mask)
2039                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
2040                 else
2041                         seq_printf(m, "%s ", hsm_policy_names[j].name);
2042         }
2043         /* remove last ' ' */
2044         m->count--;
2045         seq_putc(m, '\n');
2046 }
2047
2048 /* methods to read/write HSM policy flags */
2049 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
2050 {
2051         struct mdt_device       *mdt = m->private;
2052         struct coordinator      *cdt = &mdt->mdt_coordinator;
2053         ENTRY;
2054
2055         hsm_policy_bit2str(m, cdt->cdt_policy, false);
2056         RETURN(0);
2057 }
2058
2059 static ssize_t
2060 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
2061                          size_t count, loff_t *off)
2062 {
2063         struct seq_file         *m = file->private_data;
2064         struct mdt_device       *mdt = m->private;
2065         struct coordinator      *cdt = &mdt->mdt_coordinator;
2066         char                    *start, *token, sign;
2067         char                    *buf;
2068         __u64                    policy;
2069         __u64                    add_mask, remove_mask, set_mask;
2070         int                      rc;
2071         ENTRY;
2072
2073         if (count + 1 > PAGE_SIZE)
2074                 RETURN(-EINVAL);
2075
2076         OBD_ALLOC(buf, count + 1);
2077         if (buf == NULL)
2078                 RETURN(-ENOMEM);
2079
2080         if (copy_from_user(buf, buffer, count))
2081                 GOTO(out, rc = -EFAULT);
2082
2083         buf[count] = '\0';
2084
2085         start = buf;
2086         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
2087                start);
2088
2089         add_mask = remove_mask = set_mask = 0;
2090         do {
2091                 token = strsep(&start, "\n ");
2092                 sign = *token;
2093
2094                 if (sign == '\0')
2095                         continue;
2096
2097                 if (sign == '-' || sign == '+')
2098                         token++;
2099
2100                 policy = hsm_policy_str2bit(token);
2101                 if (policy == 0) {
2102                         CWARN("%s: '%s' is unknown, "
2103                               "supported policies are:\n", mdt_obd_name(mdt),
2104                               token);
2105                         hsm_policy_bit2str(m, 0, false);
2106                         GOTO(out, rc = -EINVAL);
2107                 }
2108                 switch (sign) {
2109                 case '-':
2110                         remove_mask |= policy;
2111                         break;
2112                 case '+':
2113                         add_mask |= policy;
2114                         break;
2115                 default:
2116                         set_mask |= policy;
2117                         break;
2118                 }
2119
2120         } while (start != NULL);
2121
2122         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
2123                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
2124
2125         /* if no sign in all string, it is a clear and set
2126          * if some sign found, all unsigned are converted
2127          * to add
2128          * P1 P2 = set to P1 and P2
2129          * P1 -P2 = add P1 clear P2 same as +P1 -P2
2130          */
2131         if (remove_mask == 0 && add_mask == 0) {
2132                 cdt->cdt_policy = set_mask;
2133         } else {
2134                 cdt->cdt_policy |= set_mask | add_mask;
2135                 cdt->cdt_policy &= ~remove_mask;
2136         }
2137
2138         GOTO(out, rc = count);
2139
2140 out:
2141         OBD_FREE(buf, count + 1);
2142         RETURN(rc);
2143 }
2144 LDEBUGFS_SEQ_FOPS(mdt_hsm_policy);
2145
2146 ssize_t loop_period_show(struct kobject *kobj, struct attribute *attr,
2147                          char *buf)
2148 {
2149         struct coordinator *cdt = container_of(kobj, struct coordinator,
2150                                                cdt_hsm_kobj);
2151
2152         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_loop_period);
2153 }
2154
2155 ssize_t loop_period_store(struct kobject *kobj, struct attribute *attr,
2156                           const char *buffer, size_t count)
2157 {
2158         struct coordinator *cdt = container_of(kobj, struct coordinator,
2159                                                cdt_hsm_kobj);
2160         unsigned int val;
2161         int rc;
2162
2163         rc = kstrtouint(buffer, 0, &val);
2164         if (rc)
2165                 return rc;
2166
2167         if (val != 0)
2168                 cdt->cdt_loop_period = val;
2169
2170         return val ? count : -EINVAL;
2171 }
2172 LUSTRE_RW_ATTR(loop_period);
2173
2174 ssize_t grace_delay_show(struct kobject *kobj, struct attribute *attr,
2175                          char *buf)
2176 {
2177         struct coordinator *cdt = container_of(kobj, struct coordinator,
2178                                                cdt_hsm_kobj);
2179
2180         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_grace_delay);
2181 }
2182
2183 ssize_t grace_delay_store(struct kobject *kobj, struct attribute *attr,
2184                           const char *buffer, size_t count)
2185 {
2186         struct coordinator *cdt = container_of(kobj, struct coordinator,
2187                                                cdt_hsm_kobj);
2188         unsigned int val;
2189         int rc;
2190
2191         rc = kstrtouint(buffer, 0, &val);
2192         if (rc)
2193                 return rc;
2194
2195         if (val != 0)
2196                 cdt->cdt_grace_delay = val;
2197
2198         return val ? count : -EINVAL;
2199 }
2200 LUSTRE_RW_ATTR(grace_delay);
2201
2202 ssize_t active_request_timeout_show(struct kobject *kobj,
2203                                     struct attribute *attr,
2204                                     char *buf)
2205 {
2206         struct coordinator *cdt = container_of(kobj, struct coordinator,
2207                                                cdt_hsm_kobj);
2208
2209         return scnprintf(buf, PAGE_SIZE, "%d\n", cdt->cdt_active_req_timeout);
2210 }
2211
2212 ssize_t active_request_timeout_store(struct kobject *kobj,
2213                                      struct attribute *attr,
2214                                      const char *buffer, size_t count)
2215 {
2216         struct coordinator *cdt = container_of(kobj, struct coordinator,
2217                                                cdt_hsm_kobj);
2218         unsigned int val;
2219         int rc;
2220
2221         rc = kstrtouint(buffer, 0, &val);
2222         if (rc)
2223                 return rc;
2224
2225         if (val != 0)
2226                 cdt->cdt_active_req_timeout = val;
2227
2228         return val ? count : -EINVAL;
2229 }
2230 LUSTRE_RW_ATTR(active_request_timeout);
2231
2232 ssize_t max_requests_show(struct kobject *kobj, struct attribute *attr,
2233                           char *buf)
2234 {
2235         struct coordinator *cdt = container_of(kobj, struct coordinator,
2236                                                cdt_hsm_kobj);
2237
2238         return scnprintf(buf, PAGE_SIZE, "%llu\n", cdt->cdt_max_requests);
2239 }
2240
2241 ssize_t max_requests_store(struct kobject *kobj, struct attribute *attr,
2242                            const char *buffer, size_t count)
2243 {
2244         struct coordinator *cdt = container_of(kobj, struct coordinator,
2245                                                cdt_hsm_kobj);
2246         unsigned long long val;
2247         int rc;
2248
2249         rc = kstrtoull(buffer, 0, &val);
2250         if (rc)
2251                 return rc;
2252
2253         if (val != 0)
2254                 cdt->cdt_max_requests = val;
2255
2256         return val ? count : -EINVAL;
2257 }
2258 LUSTRE_RW_ATTR(max_requests);
2259
2260 ssize_t default_archive_id_show(struct kobject *kobj, struct attribute *attr,
2261                                 char *buf)
2262 {
2263         struct coordinator *cdt = container_of(kobj, struct coordinator,
2264                                                cdt_hsm_kobj);
2265
2266         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_default_archive_id);
2267 }
2268
2269 ssize_t default_archive_id_store(struct kobject *kobj, struct attribute *attr,
2270                                  const char *buffer, size_t count)
2271 {
2272         struct coordinator *cdt = container_of(kobj, struct coordinator,
2273                                                cdt_hsm_kobj);
2274         unsigned int val;
2275         int rc;
2276
2277         rc = kstrtouint(buffer, 0, &val);
2278         if (rc)
2279                 return rc;
2280
2281         if (val != 0)
2282                 cdt->cdt_default_archive_id = val;
2283
2284         return val ? count : -EINVAL;
2285 }
2286 LUSTRE_RW_ATTR(default_archive_id);
2287
2288 /*
2289  * procfs write method for MDT/hsm_control
2290  * proc entry is in mdt directory so data is mdt obd_device pointer
2291  */
2292 #define CDT_ENABLE_CMD   "enabled"
2293 #define CDT_STOP_CMD     "shutdown"
2294 #define CDT_DISABLE_CMD  "disabled"
2295 #define CDT_PURGE_CMD    "purge"
2296 #define CDT_HELP_CMD     "help"
2297 #define CDT_MAX_CMD_LEN  10
2298
2299 ssize_t hsm_control_store(struct kobject *kobj, struct attribute *attr,
2300                           const char *buffer, size_t count)
2301 {
2302         struct obd_device *obd = container_of(kobj, struct obd_device,
2303                                               obd_kset.kobj);
2304         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2305         struct coordinator *cdt = &(mdt->mdt_coordinator);
2306         int usage = 0;
2307         int rc = 0;
2308
2309         if (count == 0 || count >= CDT_MAX_CMD_LEN)
2310                 return -EINVAL;
2311
2312         if (strncmp(buffer, CDT_ENABLE_CMD, strlen(CDT_ENABLE_CMD)) == 0) {
2313                 if (cdt->cdt_state == CDT_DISABLE) {
2314                         rc = set_cdt_state(cdt, CDT_RUNNING);
2315                         mdt_hsm_cdt_event(cdt);
2316                         wake_up(&cdt->cdt_waitq);
2317                 } else if (cdt->cdt_state == CDT_RUNNING) {
2318                         rc = 0;
2319                 } else {
2320                         rc = mdt_hsm_cdt_start(mdt);
2321                 }
2322         } else if (strncmp(buffer, CDT_STOP_CMD, strlen(CDT_STOP_CMD)) == 0) {
2323                 if (cdt->cdt_state == CDT_STOPPING) {
2324                         CERROR("%s: Coordinator is already stopping\n",
2325                                mdt_obd_name(mdt));
2326                         rc = -EALREADY;
2327                 } else if (cdt->cdt_state == CDT_STOPPED) {
2328                         rc = 0;
2329                 } else {
2330                         rc = mdt_hsm_cdt_stop(mdt);
2331                 }
2332         } else if (strncmp(buffer, CDT_DISABLE_CMD,
2333                            strlen(CDT_DISABLE_CMD)) == 0) {
2334                 if ((cdt->cdt_state == CDT_STOPPING) ||
2335                     (cdt->cdt_state == CDT_STOPPED)) {
2336                         /* exit gracefully if coordinator is being stopped
2337                          * or stopped already.
2338                          */
2339                         rc = 0;
2340                 } else {
2341                         rc = set_cdt_state(cdt, CDT_DISABLE);
2342                 }
2343         } else if (strncmp(buffer, CDT_PURGE_CMD,
2344                            strlen(CDT_PURGE_CMD)) == 0) {
2345                 rc = hsm_cancel_all_actions(mdt);
2346         } else if (strncmp(buffer, CDT_HELP_CMD,
2347                            strlen(CDT_HELP_CMD)) == 0) {
2348                 usage = 1;
2349         } else {
2350                 usage = 1;
2351                 rc = -EINVAL;
2352         }
2353
2354         if (usage == 1)
2355                 CERROR("%s: Valid coordinator control commands are: "
2356                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2357                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2358                        CDT_PURGE_CMD, CDT_HELP_CMD);
2359
2360         if (rc)
2361                 RETURN(rc);
2362
2363         RETURN(count);
2364 }
2365
2366 ssize_t hsm_control_show(struct kobject *kobj, struct attribute *attr,
2367                          char *buf)
2368 {
2369         struct obd_device *obd = container_of(kobj, struct obd_device,
2370                                               obd_kset.kobj);
2371         struct coordinator *cdt;
2372
2373         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2374
2375         return scnprintf(buf, PAGE_SIZE, "%s\n",
2376                          cdt_mdt_state2str(cdt->cdt_state));
2377 }
2378
2379 static int
2380 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
2381 {
2382         bool first = true;
2383         int i;
2384         ENTRY;
2385
2386         for (i = 0; i < 8 * sizeof(mask); i++) {
2387                 if (mask & (1UL << i)) {
2388                         seq_printf(m, "%s%s", first ? "" : " ",
2389                                    hsm_copytool_action2name(i));
2390                         first = false;
2391                 }
2392         }
2393         seq_putc(m, '\n');
2394
2395         RETURN(0);
2396 }
2397
2398 static int
2399 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2400 {
2401         struct mdt_device *mdt = m->private;
2402         struct coordinator *cdt = &mdt->mdt_coordinator;
2403
2404         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2405 }
2406
2407 static int
2408 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2409 {
2410         struct mdt_device *mdt = m->private;
2411         struct coordinator *cdt = &mdt->mdt_coordinator;
2412
2413         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2414 }
2415
2416 static int
2417 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2418 {
2419         struct mdt_device *mdt = m->private;
2420         struct coordinator *cdt = &mdt->mdt_coordinator;
2421
2422         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2423 }
2424
2425 static inline enum hsm_copytool_action
2426 hsm_copytool_name2action(const char *name)
2427 {
2428         if (strcasecmp(name, "NOOP") == 0)
2429                 return HSMA_NONE;
2430         else if (strcasecmp(name, "ARCHIVE") == 0)
2431                 return HSMA_ARCHIVE;
2432         else if (strcasecmp(name, "RESTORE") == 0)
2433                 return HSMA_RESTORE;
2434         else if (strcasecmp(name, "REMOVE") == 0)
2435                 return HSMA_REMOVE;
2436         else if (strcasecmp(name, "CANCEL") == 0)
2437                 return HSMA_CANCEL;
2438         else
2439                 return -1;
2440 }
2441
2442 static ssize_t
2443 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2444                             size_t user_count, __u64 *mask)
2445 {
2446         char *buf, *pos, *name;
2447         size_t buf_size;
2448         __u64 new_mask = 0;
2449         int rc;
2450         ENTRY;
2451
2452         if (!(user_count < 4096))
2453                 RETURN(-ENOMEM);
2454
2455         buf_size = user_count + 1;
2456
2457         OBD_ALLOC(buf, buf_size);
2458         if (buf == NULL)
2459                 RETURN(-ENOMEM);
2460
2461         if (copy_from_user(buf, user_buf, buf_size - 1))
2462                 GOTO(out, rc = -EFAULT);
2463
2464         buf[buf_size - 1] = '\0';
2465
2466         pos = buf;
2467         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2468                 int action;
2469
2470                 if (*name == '\0')
2471                         continue;
2472
2473                 action = hsm_copytool_name2action(name);
2474                 if (action < 0)
2475                         GOTO(out, rc = -EINVAL);
2476
2477                 new_mask |= (1UL << action);
2478         }
2479
2480         *mask = new_mask;
2481         rc = user_count;
2482 out:
2483         OBD_FREE(buf, buf_size);
2484
2485         RETURN(rc);
2486 }
2487
2488 static ssize_t
2489 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2490                                         size_t count, loff_t *off)
2491 {
2492         struct seq_file         *m = file->private_data;
2493         struct mdt_device       *mdt = m->private;
2494         struct coordinator *cdt = &mdt->mdt_coordinator;
2495
2496         return mdt_write_hsm_request_mask(file, buf, count,
2497                                            &cdt->cdt_user_request_mask);
2498 }
2499
2500 static ssize_t
2501 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2502                                         size_t count, loff_t *off)
2503 {
2504         struct seq_file         *m = file->private_data;
2505         struct mdt_device       *mdt = m->private;
2506         struct coordinator      *cdt = &mdt->mdt_coordinator;
2507
2508         return mdt_write_hsm_request_mask(file, buf, count,
2509                                            &cdt->cdt_group_request_mask);
2510 }
2511
2512 static ssize_t
2513 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2514                                         size_t count, loff_t *off)
2515 {
2516         struct seq_file         *m = file->private_data;
2517         struct mdt_device       *mdt = m->private;
2518         struct coordinator      *cdt = &mdt->mdt_coordinator;
2519
2520         return mdt_write_hsm_request_mask(file, buf, count,
2521                                            &cdt->cdt_other_request_mask);
2522 }
2523
2524 static ssize_t remove_archive_on_last_unlink_show(struct kobject *kobj,
2525                                                   struct attribute *attr,
2526                                                   char *buf)
2527 {
2528         struct coordinator *cdt = container_of(kobj, struct coordinator,
2529                                                cdt_hsm_kobj);
2530
2531         return scnprintf(buf, PAGE_SIZE, "%u\n",
2532                          cdt->cdt_remove_archive_on_last_unlink);
2533 }
2534
2535 static ssize_t remove_archive_on_last_unlink_store(struct kobject *kobj,
2536                                                    struct attribute *attr,
2537                                                    const char *buffer,
2538                                                    size_t count)
2539 {
2540         struct coordinator *cdt = container_of(kobj, struct coordinator,
2541                                                cdt_hsm_kobj);
2542         bool val;
2543         int rc;
2544
2545         rc = kstrtobool(buffer, &val);
2546         if (rc < 0)
2547                 return rc;
2548
2549         cdt->cdt_remove_archive_on_last_unlink = val;
2550         return count;
2551 }
2552 LUSTRE_RW_ATTR(remove_archive_on_last_unlink);
2553
2554 LDEBUGFS_SEQ_FOPS(mdt_hsm_user_request_mask);
2555 LDEBUGFS_SEQ_FOPS(mdt_hsm_group_request_mask);
2556 LDEBUGFS_SEQ_FOPS(mdt_hsm_other_request_mask);
2557
2558 /* Read-only sysfs files for request counters */
2559 static ssize_t archive_count_show(struct kobject *kobj, struct attribute *attr,
2560                                   char *buf)
2561 {
2562         struct coordinator *cdt = container_of(kobj, struct coordinator,
2563                                                cdt_hsm_kobj);
2564
2565         return scnprintf(buf, PAGE_SIZE, "%d\n",
2566                          atomic_read(&cdt->cdt_archive_count));
2567 }
2568 LUSTRE_RO_ATTR(archive_count);
2569
2570 static ssize_t restore_count_show(struct kobject *kobj, struct attribute *attr,
2571                                   char *buf)
2572 {
2573         struct coordinator *cdt = container_of(kobj, struct coordinator,
2574                                                cdt_hsm_kobj);
2575
2576         return scnprintf(buf, PAGE_SIZE, "%d\n",
2577                          atomic_read(&cdt->cdt_restore_count));
2578 }
2579 LUSTRE_RO_ATTR(restore_count);
2580
2581 static ssize_t remove_count_show(struct kobject *kobj, struct attribute *attr,
2582                                  char *buf)
2583 {
2584         struct coordinator *cdt = container_of(kobj, struct coordinator,
2585                                                cdt_hsm_kobj);
2586
2587         return scnprintf(buf, PAGE_SIZE, "%d\n",
2588                          atomic_read(&cdt->cdt_remove_count));
2589 }
2590 LUSTRE_RO_ATTR(remove_count);
2591
2592 static struct ldebugfs_vars ldebugfs_mdt_hsm_vars[] = {
2593         { .name =       "agents",
2594           .fops =       &mdt_hsm_agent_fops                     },
2595         { .name =       "actions",
2596           .fops =       &mdt_hsm_actions_fops,
2597           .proc_mode =  0444                                    },
2598         { .name =       "policy",
2599           .fops =       &mdt_hsm_policy_fops                    },
2600         { .name =       "active_requests",
2601           .fops =       &mdt_hsm_active_requests_fops           },
2602         { .name =       "user_request_mask",
2603           .fops =       &mdt_hsm_user_request_mask_fops,        },
2604         { .name =       "group_request_mask",
2605           .fops =       &mdt_hsm_group_request_mask_fops,       },
2606         { .name =       "other_request_mask",
2607           .fops =       &mdt_hsm_other_request_mask_fops,       },
2608         { 0 }
2609 };
2610
2611 static struct attribute *hsm_attrs[] = {
2612         &lustre_attr_loop_period.attr,
2613         &lustre_attr_grace_delay.attr,
2614         &lustre_attr_active_request_timeout.attr,
2615         &lustre_attr_max_requests.attr,
2616         &lustre_attr_default_archive_id.attr,
2617         &lustre_attr_remove_archive_on_last_unlink.attr,
2618         &lustre_attr_archive_count.attr,
2619         &lustre_attr_restore_count.attr,
2620         &lustre_attr_remove_count.attr,
2621         NULL,
2622 };
2623
2624 KOBJ_ATTRIBUTE_GROUPS(hsm); /* creates hsm_groups from hsm_attrs */
2625
2626 static void hsm_kobj_release(struct kobject *kobj)
2627 {
2628         struct coordinator *cdt = container_of(kobj, struct coordinator,
2629                                                cdt_hsm_kobj);
2630
2631         debugfs_remove_recursive(cdt->cdt_debugfs_dir);
2632         cdt->cdt_debugfs_dir = NULL;
2633
2634         complete(&cdt->cdt_kobj_unregister);
2635 }
2636
2637 static struct kobj_type hsm_ktype = {
2638         .default_groups = KOBJ_ATTR_GROUPS(hsm),
2639         .sysfs_ops      = &lustre_sysfs_ops,
2640         .release        = hsm_kobj_release,
2641 };
2642
2643 /**
2644  * create sysfs entries for coordinator
2645  * \param mdt [IN]
2646  * \retval 0 success
2647  * \retval -ve failure
2648  */
2649 int hsm_cdt_tunables_init(struct mdt_device *mdt)
2650 {
2651         struct coordinator *cdt = &mdt->mdt_coordinator;
2652         struct obd_device *obd = mdt2obd_dev(mdt);
2653         int rc;
2654
2655         init_completion(&cdt->cdt_kobj_unregister);
2656         rc = kobject_init_and_add(&cdt->cdt_hsm_kobj, &hsm_ktype,
2657                                   &obd->obd_kset.kobj, "%s", "hsm");
2658         if (rc) {
2659                 kobject_put(&cdt->cdt_hsm_kobj);
2660                 return rc;
2661         }
2662
2663         /* init debugfs entries, failure is not critical */
2664         cdt->cdt_debugfs_dir = debugfs_create_dir("hsm",
2665                                                   obd->obd_debugfs_entry);
2666         ldebugfs_add_vars(cdt->cdt_debugfs_dir, ldebugfs_mdt_hsm_vars, mdt);
2667
2668         return 0;
2669 }
2670
2671 /**
2672  * remove sysfs entries for coordinator
2673  *
2674  * @mdt
2675  */
2676 void hsm_cdt_tunables_fini(struct mdt_device *mdt)
2677 {
2678         struct coordinator *cdt = &mdt->mdt_coordinator;
2679
2680         kobject_put(&cdt->cdt_hsm_kobj);
2681         wait_for_completion(&cdt->cdt_kobj_unregister);
2682 }