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