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